Reputation:
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.
Upvotes: 8
Views: 2436
Reputation: 516
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.
Upvotes: 10
Reputation: 5793
You'll need to define the explicit through table if you want to access it through the ORM.
Given the way you've defined the relationship you have
person = Person.objects.get(id=x)
groups = person.members_set.all()
and
groups = Group.objects.get(id=x)
members = group.members
Otherwise you'll need to access the table through Raw SQL query
Upvotes: 1