Search code examples
djangomany-to-many

How to query the implicit through table in django (ManyToMany field)?


In the django documentation it reads the following:

If you don’t specify an explicit through model, there is still an implicit through model class you can use to directly access the table created to hold the association.

However, I can not find out how I can access this table. Say I have this structure:

class Person(models.Model):
    name = models.CharField(max_length=50)

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person)

And I would like to query the table that holds the person_groups (the implicit through table)... how do I do this?

PersonGroup.objects.all()

That does not work, and I can't find what syntax I should be using.


Solution

  • In your case it'll be like Group.members.through.objects.all()

    I.e. Group.members.through returns a model class like <class 'appname.models.Group_person'>

    But I am still not sure that this will make your query more effective. You always can filter on one table, then filter its members or persons.