Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (45.3k points)

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'))

1 Answer

0 votes
by (16.8k points)

​​​​​​The related_name attribute specifies the name of the reverse relation from the User 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 instance User.map_set.all().

If you do specify, e.g. related_name=maps on the User model, User.map_set will still work, but the User.maps. syntax is obviously a bit cleaner and less clunky; so for example, if you had a user object current_user, you could use current_user.maps.all() to get all instances of your Map model that have a relation to current_user.

Browse Categories

...