DEV Community

Cover image for using related_name in Django
Ankit Kumar
Ankit Kumar

Posted on

using related_name in Django

In this Blog we are going to talk about, How to use the related_name parameter in Django. When we create any type of relating in Django, Django by Default creates a backward relating or you can say it is a reverse relation. with the related_name attribute, we can give a name to the reverse relation.

Let’s try to understand this with an example:-

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class Note(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    content = models.TextField()
Enter fullscreen mode Exit fullscreen mode

in the upper model, we have one too many relations, a user can create as many notes as many he wants. Lets’ try to access all the notes of a currently logged-in user

def get_notes(request):
    user = request.user
    notes = Notes.objects.filter(user = user)    
    context = {
        "notes":notes
    }
    return render(request, 'home.html',context)
Enter fullscreen mode Exit fullscreen mode

Here we directly access all the notes of currently logged-in users using the Notes model, now let’s say I don’t want to use the Notes model to access notes of currently logged-in users, I want to access Notes for the currently logged-in user using reverse relation. We already know that Django by default creates reverse relations and we can use that relationship with the _set object. Here we are trying to get all the notes of currently logged-in users.

def get_notes(request):
    user = request.user   
    notes = user.notes_set.all()
    context = {
        "notes":notes
    }
    return render(request, 'home.html',context)
Enter fullscreen mode Exit fullscreen mode

Here we can access all the todos of the currently logged-in users, using _set object.

Now let’s add the related_name attribute and see what changes and simplicity it provides.

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class Note(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="notes")
    content = models.TextField()
Enter fullscreen mode Exit fullscreen mode

In the above code we have added related_name = "notes" parameter.

def get_notes(request):

    user = request.user
    notes = user.notes.all()
    context = {
        "notes":notes
    }
    return render(request, 'home.html',context)
Enter fullscreen mode Exit fullscreen mode

As you can see using the related name attribute make our code more readable, you can use the related name attribute in all types of model relations in Django. If you want to disable Django's default reverse relation then you can add related_name = “+” and this will disable Django's default reverse relation.

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class Note(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="+")
    content = models.TextField()
Enter fullscreen mode Exit fullscreen mode

this will disable Django's default relation.

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Neon image

Set up a Neon project in seconds and connect from a Python application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay