2

新手问题...

楷模:

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)

这可能吗?

4

1 回答 1

2

你可以试试:

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 中具有属性的对象的集合。

于 2012-07-10T04:55:24.593 回答