What is the related_name
argument useful for on ManyToManyField
and ForeignKey
fields? For example, given the following code, what is the effect of related_name='maps'
?
class Map(db.Model):
members = models.ManyToManyField(User, related_name='maps',
verbose_name=_('members'))
The related name parameter is actually an option. If we do not set it, Django automatically creates the other side of the relation for us. In the case of the Map model, Django would have created a
map_set
attribute, allowing access viam.map_set
in your example(m being your class instance). The formula Django uses is the name of the model followed by the string_set
. The related name parameter thus simply overrides Django’s default rather than providing new behavior.To add to existing answer - related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material
So when you will have to access this data you only can use related name
It is not working otherwise (at least I was not able to skip the usage of related name in case of 2 FK's to the same table.)
The
related_name
argument is also useful if you have more complex related class names. For example, if you have a foreign key relationship:In order to access
UserMapDataFrame
objects from the relatedUser
, the default call would beUser.usermapdataframe_set.all()
, which it is quite difficult to read.Using the
related_name
allows you to specify a simpler or more legible name to get the reverse relation. In this case, if you specifyuser = models.ForeignKey(User, related_name='map_data')
, the call would then beUser.map_data.all()
.The
related_name
attribute specifies the name of the reverse relation from theUser
model back to your model.If you don't specify a
related_name
, Django automatically creates one using the name of your model with the suffix_set
, for instanceUser.map_set.all()
.If you do specify, e.g.
related_name=maps
on theUser
model,User.map_set
will still work, but theUser.maps.
syntax is obviously a bit cleaner and less clunky; so for example, if you had a user objectcurrent_user
, you could usecurrent_user.maps.all()
to get all instances of yourMap
model that have a relation tocurrent_user
.The Django documentation has more details.