related_name in Django is an attribute that is used to specify the name of the
Manager that returns the instances of the source model in the model’s relationship i.e the name to use for the reverse filter from the target model (backward relation).
If you don’t specify the
related_name for the backward relation, by default, Django will use the name of the source model with the suffix
_set as the
For example, in the following code snippet, the
ForeignKeyField does not have
class Blog(models.Model): name = models.CharField(max_length=20) class Post(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
So to filter the
Post (source model) from the instance of the
Blog (target model), you will have to use the
post_set as the filter name.
>>> b = Blog.objects.get(id=1) >>> b.post_set.all() # Returns all Post objects related to Blog
You can override the
post_set by setting the
related_name parameter in the
... class Post(models.Model): blog = models.ForeignKey(Blog, related_name='posts', on_delete=models.CASCADE)
Now you can filter
Post from the instance of
Blog like this:
>>> b = Blog.objects.get(id=1) >>> b.posts.all() # Returns all Post objects related to Blog
Where can you use ‘related_name’ attribute?
You can use
related_name attribute (for naming the backward relation) in the relationship fields. These are those fields that refer to other models or represent relationships. For example,
This Post Has 2 Comments
Thanks, Green, for pointing out. I have updated the post.