gpt4 book ai didi

python - Django 过滤器未返回正确的结果

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:32 25 4
gpt4 key购买 nike

我有一个 View ,我试图按类别过滤产品。

class ProductListView(ListView):
context_object_name = 'products'
model = models.Product
template_name = "catalogue/catalogue.html"
products = Product.objects.filter(category__name="Biryani Dishes")

所以我有一个名为“Biryani Dishes”的类别。我收到错误 ValueError: invalidliteral for int() with base 10: 'Biryani Dishes'

如果我将查询更改为 (name='Chicken Biryani'),我会取回所有产品。 (我期待只有鸡肉印度比尔亚尼菜)。

理想情况下,我想创建一个通用查询,将类别作为参数,并且我可以在 HTML 模板上指定实际名称。

非常感谢任何帮助。

模型.py

from django.db import models
from django.core.urlresolvers import reverse

class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)

class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'

def __str__(self):
return self.name

# def get_absolute_url(self):
# return reverse('shop:product_list_by_category', args=[self.slug])

class Product(models.Model):
category = models.ForeignKey(Category, related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

class Meta:
ordering = ('-created',)
index_together = (('id', 'slug'),)

def __str__(self):
return self.name

# def get_absolute_url(self):
# return reverse('shop:product_detail', args=[self.id, self.slug])

模板代码:

            {% for product in products %}
<tr>
<td><h5>{{ product.name }}</h5>
<p>Cooked with chicken and mutton cumin spices</p></td>
<td><p><strong>£ {{ product.price }}</strong></p></td>
<td class="options"><a href="#0"><i class="icon_plus_alt2"></i></a></td>
</tr>
{% endfor %}

最佳答案

您应该将category更改为category__name。所以你会:

class ProductListView(ListView):
context_object_name = 'products'
model = models.Product
template_name = "catalogue/catalogue.html"
products = Product.objects.all()
birdish = Product.objects.filter(category__name="Biryani Dishes")

如果要比较的变量是 pk 或模型本身的实例,则只能按类别进行过滤。

关于python - Django 过滤器未返回正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48532194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com