I’m creating a Person Group and Membership as described in Django docs for intermediate model.
class Person(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __unicode__(self):
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
It is possible to access the Person from a Group object with:
>>>Group.members.name
Does Django creates another query to fetch the Person?
Can I access the date_joined field from a Group object?
The thing that confuses me is that I would expect to get the Person name field with:
>>>Group.members.person.name
What happens if a Person has a field ‘name’ and also the intermediate model have a field ‘name’.
The members field in your example is a ManyToManyField, so it’s a way to access many people rather than one person.
The object that is under the members field is actually a special type of Manager, not a Person:
To understand better what a Manager is, see the documentation.
To access a person’s name you would do for example:
You cannot access the fields in your Membership model via the Manager in the members field. To access any of the fields in it you would do:
And so if you had a field called name in your Membership model, you would access it like this:
A second way to access a Person’s name would be:
Note that
membership_setis a default name for the manager pointing towards the membership, but it can be changed by specifyingrelated_namein the corresponding foreign key. For example if the foreign key from theMembershipto theGroupwould be defined like such:Then you would access the manager using
group_members:Hope that helps a little 🙂