Search code examples
djangomodelsmany-to-manymanytomanyfield

Querying django ManyToMany


I have got

Foo <=> FooGroup <=> Bar

relation, where <=> stands for ManyToMany field.

How do I retrieve all the Foos for a specific Bar instance?


Solution

  • Here's an example with auth models, where the relationship is very much like your structure : User <=> Groups <=> Permission

    from django.contrib.auth import models
    models.Permission.objects.filter(group__user=models.User.objects.get(username="webmaster"))
    

    With your example:

    Foo.objects.filter(foogroup__bar=barinstance)