tags:

views:

36

answers:

2

Say I have 2 classes as:

class Bar(models.Model):
   prop = IntegerField()

class Foo(models.Model):
   bar = ManyToManyField(Bar)

I want to return a QuerySet containing model instances of bar that match the query:

QuerySetOfFoos.objects.filter(bar__prop__gt=0)

Is there an easy way to do this? I know that in the model instance I could do foo.bar_set but not sure how to do it over all of the original QuerySet...

A: 

Do you mean something like this:

Bar.objects.filter(foo__bar__prop__gt = 0)

?

Lukasz Dziedzia
Not quite since that would be from all Bars, not just those bars that are in a M2M with the queryset 'QuerySetOfFoos' however that is a handy thing to know!
Doug-W
+1  A: 

If you want to get a QuerySet of Bars, you need to start with the Bar manager, i.e. Bar.objects. This will work:

Bar.objects.filter(foo__in=QuerySetOfFoos, prop__gt=0)

Ideally, you should simply include whatever parameters were used to get QuerySetOfFoos in your query. For example, if your Foos had "group" and "rank" fields, and you wanted all Bars for Foos with group "members" and rank > 10, you would do:

Bar.objects.filter(foo__group='members', foo__rank__gt=10, prop__gt=0)
Aram Dulyan
That is exactly what I was looking for, m2m__in, as well as just recalling that you can think of the m2m relationship from both directions which is something that slips my mind occasionally.
Doug-W