我正在尝试过滤类别名称为“书籍”的所有产品。请参阅下面我尝试过的内容,但我得到一个空的查询集。这是我models.py的以防万一:from django.db import modelsfrom 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 回答

一只名叫tom的猫
TA贡献1906条经验 获得超3个赞
使用数据库工具检查数据库后,我意识到Category
ForeignKey 是NULL
. 问题是我在保存父母之前分配了父母,这意味着他们没有 PrimaryKey,所以 ForeignKey 设置为NULL
.
- 1 回答
- 0 关注
- 166 浏览
添加回答
举报
0/150
提交
取消