新手问题......
型号:
Item(model.Models):
...
attributes = models.ManyToManyField('Attributes', null=True)
...
Attributes(models.Models):
title = models.CharField(max_length=100, unique = True)
value = models.TextField()
...
我有一个属性对象列表[attObj1, attobj2, attObj3, attObjN]
,我想在过滤Item
表时使用它。以下查询有效。
items = Item.objects.filter(attributes = attObj1 and attObj2 and attObj3)
问题 是我需要动态创建查询(即:attObj1 and attObj2 and attObj3... and attObjN
),因为列表中的属性数量未知。
我尝试使用以下复杂查询集没有运气(source)。它返回了一个空列表。
attList = [attObj1, attObj2, attObj3]
query = Q(attributes = attList.pop(0))
for att in attList:
query = query & Q(attributes=att)
items = Item.objects.filter(query)
这可能吗?
答案 0 :(得分:3)
您可以尝试:
items = Item.objects.filter(attributes__in=attList)
编辑: 您也可以尝试链接/多个过滤器
attList = [attObj1, attObj2, attObj3]
fitems = Items.objects.filter()
for att in attList:
fitems = fitems.filter(attributes=att)
fitems
被简化为包含在attList中具有属性的对象的集合。