Why use the through argument for ManyToManyField in Django models?

Looking through Django docs and trying to figure out the use of the through argument Here is the link to the doc .

Example:

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) 

Why is the group members attribute even needed? Isn't the "group" ForeignKey of Membership enough to keep track of the relationship and gain access to this information?

+6
source share
4 answers

I think you are thinking too much about it. Say you did not use through :

 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) def __unicode__(self): return self.name 

Django, behind the scenes, essentially creates the following model for you:

 class GroupPerson(models.Model) group = models.ForeignKey(Group) person = models.ForeignKey(Person) 

The reason for creating the Membership model is to add additional data that Django automatically creates by default by default, it will not by default, but since you no longer use the default value, you have to tell Django that using through . Basically, you keep the Django API for ManyToManyFields.

+9
source

The reason for this is that the Group has a field for this relationship, instead of following the relationship through its set_name.

If nothing else, this will simplify write requests. At the very least, it can make life easier for the programmer, and the code is easier to read. A sufficiently optimized ORM could generate the appropriate indexes to speed up such access (and if I'm not mistaken, django really does this, or at least the South).

+3
source

This is so that you can directly contact members from a group. You don’t necessarily want to access Membership objects directly (my user never even sees them). You just need groups with some additional information. Consider membership in the metadata about the relationship between the Person and the Group.

+2
source

through tables are used to store relationship properties, in this case, for example. date a Person joined a specific Group

+1
source

Source: https://habr.com/ru/post/905738/


All Articles