In the Django documentation about related_name
it says the following:
The name to use for the relation from the related object back to th
When you create a foreign key, you are linking two models together. The model with the ForeignKey()
field uses the field name to look up the other model. It also implicitly adds a member to the linked model referring back to this one.
class Post(models.Model):
# ... fields ...
class Comment(models.Model):
# ... fields ...
post = models.ForeignKey(Post, related_name=???)
There are three possible scenarios here:
related_name
If you don't specify a name, django will create one by default for you.
some_post = Post.objects.get(id=12345)
comments = some_post.comment_set.all()
The default name is the relation's name + _set
.
Usually you want to specify something to make it more natural. For example, related_name="comments"
.
some_post = Post.objects.get(id=12345)
comments = some_post.comments.all()
Sometimes you don't want to add the reference to the foreign model, so use related_name="+"
to not create it.
some_post = Post.objects.get(id=12345)
comments = some_post.comment_set.all() # <-- error, no way to access directly
related_query_name
is basically the same idea, but when using filter()
on a queryset:
posts_by_user = Post.objects.filter(comments__user__id=123)
But to be honest I've never used this since the related_name
value is used by default.