新手问题...
楷模:
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
:),因为列表中的属性数量是未知的。
我尝试使用以下复杂的查询集但没有运气(来源)。它返回一个空列表。
attList = [attObj1, attObj2, attObj3]
query = Q(attributes = attList.pop(0))
for att in attList:
query = query & Q(attributes=att)
items = Item.objects.filter(query)
这可能吗?