Django过滤器没有返回正确的结果

时间:2018-01-30 23:35:31

标签: python django django-models django-templates django-views

我有一个视图,我想按类别过滤产品。

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:int()的无效文字,基数为10:'Biryani Dishes'

如果我将查询更改为(name ='Chicken Biryani'),我会收回所有产品。 (我期待鸡Biryani)。

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

非常感谢任何帮助。

Models.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 %} 

2 个答案:

答案 0 :(得分:1)

您应该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")

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

答案 1 :(得分:0)

需要定义Queryset,而不是产品,这就是它返回所有记录的原因。

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