Sreeraj Chundayil
Sreeraj Chundayil

Reputation: 5859

why is related_name plural for ForeignKey?

Currently I am reading

Django 4 By Example - Fourth Edition

We are creating a Post model in blog app. The table is named as blog_post as per the sqlmigrate commands.

But when we add a ForeignKeyfrom Post to User model by

author = models.ForeignKey(User, on_delete=models.CASCADE,
                           related_name='blog_posts')

the related_name is blog_posts instead of blog_post.

Why is it in plural instead of the actual table name?

Upvotes: 1

Views: 545

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477533

The related_name=… parameter [Django-doc] is used to query items in reverse. In this case it means that for a given User (author), you can retrieve all the Posts that author has written with:

my_user.blog_posts.all()

Since there can be zero, one, or more such Posts, this is a collection, and hence it is usually written in plural form. my_user.blog_post.all() would hint that this is a single item, which is not the case.

If you do not specify a name, the default for related_name=… will be modelname_set, with modelname the name of the model in lowercase, so post_set, again to hint that this is a collection of Post objects.

For a OneToOneField [Django-doc] the related_name=… is usually singular, since then there would only be at most one such Post. The default for the related_name=… for a OneToOneField is therefore modelname, so here it would be post.


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Upvotes: 2

Related Questions