related_name – Django Built-in Field Validation
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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
field_name = models.Field(related_name="name")
Illustration of related_name=”name” using an Example. Consider a project named suorganizer(start up organizer) having an app named organizer.
Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django ? How to Create an App in Django ?
Enter the following code into models.py file of organizer app.
After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance using None from Django shell. To start Django shell, enter the command.
Python manage.py shell
Now let us try to create instance of Tag and Post using None.
# importing required model from organizer.models import Tag, Post # creating instance of Tag model r = Tag.objects.create(name ="django") r.save() # creating instance of Post model s = Post.objects.create(title ="About django") s.save() # accessing objects t = Tag.objects.get(name ="django") p = Post.objects.get(title ="About django") # method1--adding tag to post using post object p.tags.add(t) # method2--adding tag to post using tag object # which is possible with related_name t.blog_posts.add(p)
Let us check in admin interface if the instance of model is created.
1. Tag object:
In Django we only ever specify symmetric relations in a single place. The related_name parameter is what defines the other side of a relation. Concretely, given a Post instance p, the tags associated with this post are accessible via p.tags. However, given a Tag instance t, we had not explicitly defined a variable to access Post objects. Thanks to the related_name option, we may now access the list of blog posts related to the tag t via the blog posts attribute, as in t.blog_posts. The related _name parameter is actually an option. If we do not set it, Django automatically creates the other side of the relation for us. In the case of the Tag model, Django would have created a post_set attribute, allowing access via t.post_set in our example. The formula Django uses is the name of the model followed by the string_set. The related name parameter thus simply overrides Django’s default rather than providing new behavior.