4

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. :)

1 Answer 1

6

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.