Alex
Alex

Reputation: 397

Django filter across many to many field

This is a simplified version of my models:

class User(models.Model):
    pass

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

class Bar(models.Mode)
    pass

I have a user instance and I would like to compute a queryset for all Bar instances associated with that user. Going from user to Bar consists of getting all Foo objects that have user as owner and then getting all bar instances associated with each Foo.

How can I express this most efficiently using django queries?

Upvotes: 0

Views: 36

Answers (1)

cezar
cezar

Reputation: 12012

Add related names to your model Foo. This will facilitate the writing of queries.

class Foo(models.Model):
    owners = models.ManyToManyField('User', related_name='foo')
    bar = models.ForeignKey('Bar', related_name='foo')

Now assuming that you have a single user instance as you mentioned, you could make a query like this:

user = User.objects.get(pk=1)
qs = Bar.objects.filter(foo__owners=user)

If you by most efficient mean the performance and not the expression, then you should take a look at prefetch_related and select_related methods of QuerySet.

Upvotes: 1

Related Questions