Django ORM: filter using a list of objects with "and" functionality

New question ...

Models:

Item(model.Models):
    ...
    attributes = models.ManyToManyField('Attributes', null=True)
    ...


Attributes(models.Models):
    title = models.CharField(max_length=100, unique = True)
    value = models.TextField()
    ...

I have a list of attribute objects [attObj1, attobj2, attObj3, attObjN]that I want to use when filtering a table Item. The following query is executed.

items = Item.objects.filter(attributes = attObj1 and attObj2 and attObj3)

The problem is that I need to dynamically create a query (i.e. attObj1 and attObj2 and attObj3... and attObjN), since the number of attributes in the list is unknown.

I tried using the following complex query with no luck ( source ). He returned an empty list.

attList = [attObj1, attObj2, attObj3]
query = Q(attributes = attList.pop(0))
for att in attList:
    query = query & Q(attributes=att)

items = Item.objects.filter(query)

Is it possible?

+2
source share
1 answer

You can try:

items = Item.objects.filter(attributes__in=attList)

EDIT: You can also try chaining / multiple filters.

attList = [attObj1, attObj2, attObj3]
fitems = Items.objects.filter()
for att in attList:
     fitems = fitems.filter(attributes=att)

fitems , , attList.

+3

All Articles