Search code examples
djangodjango-querysetmanytomanyfield

ManyToMany field values from queryset


Suppose i have this model:

Class Item(models.Model):
    ...

Class ItemCollection(models.Model):
    ...
    items = models.ManyToManyField(Item)
    ...

Now i filter ItemCollection:

collection = RuleRequest.objects.filter(*some_filter*)

Now from the "collections" queryset i need to get all unique Items from ManyToManyField. This is easily done for a single object, but how to do it with queryset?


Solution

  • Not sure if this is what you are asking... but if you simply want to get unique Items filtered by ItemCollection the bellow should work:

    Item.objects.filter(itemcollection__*somefilter*).distinct()
    

    e.g if ItemCollection has active field

    Item.objects.filter(itemcollection__active=True).distinct()