Reputation: 5859
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 ForeignKey
from 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
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 Post
s that author has written with:
my_user.blog_posts.all()
Since there can be zero, one, or more such Post
s, this is a collection, and hence it is usually written in plural form. my_user.
would hint that this is a single item, which is not the case.blog_post.all()
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 theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
Upvotes: 2