根据特定类别名称过滤对象

时间:2019-09-25 19:38:10

标签: python django

我正在尝试过滤所有类别名称为“图书”的产品。请参阅下面的内容,但我得到的查询集为空。

这里是我的models.py,以防万一:

from django.db import models
from django.urls import reverse

[...]      

class Product(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    price = models.DecimalField(decimal_places=2, max_digits=10)
    year = models.PositiveSmallIntegerField()
    image = models.ImageField(upload_to=get_image_path, blank=True, null=True)
    date_added = models.DateTimeField(auto_now=True, null=True)
    category = models.ForeignKey('Category', on_delete=models.CASCADE)

    [...]

class Category(models.Model):
    parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

我已经尝试过了:

>>> from products.models import Product, Category
>>> c = Category(name='Books')
>>> c1 = Category(name='Textbooks', parent=c)
>>> c2 = Category(name='Primary school', parent=c1)
>>> p = Product(title='spam', description='spameggs', price=200, year=2018, category=c2)
>>> for x in (c, c1, c2, p):
...     x.save()
... 
>>> Product.objects.get(category=c2)
<Product: Product object (1)>
>>> Product.objects.filter(category__name='Books')
<QuerySet []>
>>> Product.objects.filter(Q(category__name='Books') | Q(category__parent__name='Books') | Q(category__parent__parent__name="Books"))
<QuerySet []>

1 个答案:

答案 0 :(得分:0)

使用数据库工具检查数据库后,我意识到Category ForeignKey是NULL。问题是我在保存父项之前先分配了父项,这意味着他们没有主键,因此ForeignKey设置为NULL