Django: queryset filter for *all* values from a ManyToManyField
-
12-09-2019 - |
Question
Hi (sorry for my bad english :p)
Imagine these models :
class Fruit(models.Model):
# ...
class Basket(models.Model):
fruits = models.ManyToManyField(Fruit)
Now I would like to retrieve Basket instances related to all fruits. The problem is that the code bellow returns Basket instances related to any fruits :
baskets = Basket.objects.filter(fruits__in=Fruit.objects.all())
# This doesn't work:
baskets = Basket.objects.filter(fruits=Fruit.objects.all())
Any solution do resolve this problem ?
Thank you very much. :)
Solution
I don't have a dataset handy to test this, but I think it should work:
Basket.objects.annotate(num_fruits=Count('fruits')).filter(num_fruits=len(Fruit.objects.all()))
It annotates every basket object with the count of related fruits and filters out those baskets that have a fruit count that equals the total amount of fruits.
Note: you need Django 1.1 for this to work.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow