8

i have an issue with the code in django framework regarding to related_name and related_query_name in django. please django expert explain the related_name in django, the code is below:

related_name='+'

Zeeshan Tariq
  • 103
  • 1
  • 9

1 Answers1

26

Related Name

Django maintains backward relation on each object for easy access to related objects. Suppose you have two models named "School" and "Student" and one school can have multiple students. So you will have model definition something like this

class School(models.Model):
    name = models.CharField(max_length=55)
    city = models.Charfield(max_length=55)

class Student(models.Model):
    name = models.CharField(max_length=55)
    school = models.ForeignKey(School)

Now if you have an school objects then you can access all students of that school with writing query explictly.

school = School.objects.get(id=1)
# Now if need all students of this school, first thing that come in your mind would be
Student.objects.filter(school=school)
# But instead of this, you can access all students by
school.student_set.all()

Here student_set is the default, related name made by Django. But you can have your custom related names like this

class Student(models.Model):
    name = models.CharField(max_length=55)
    school = models.ForeignKey(School, related_name='students')
# Now you can do
school.students.all()

Special Character in related name

If you define related_name='+' then backward relation would not be available on object and school.student_set.all() will give you error.

If you’d prefer Django not to create a backwards relation, set related_name to '+' or end it with '+'. For example, this will ensure that the User model won’t have a backwards relation to this model:

Related Query Name

related_query_name is similar to related_name but it gets used in queryset.

If you need to apply some filter on student via school model, then you would do

School.objects.filter(student__name='abc')

But if you define related_query_name then you can do

class Student(models.Model):
    name = models.CharField(max_length=55)
    school = models.ForeignKey(School, related_query_name='abc')
# Now you can do
School.objects.filter(abc__name='abc')

Refer doc for further reference: https://docs.djangoproject.com/en/3.0/ref/models/fields/

SHIVAM JINDAL
  • 2,844
  • 1
  • 17
  • 34
  • 3
    This is the only explanation with full example, thank you very much I was totally confused before reading this – Akshat Tamrakar Jul 16 '21 at 17:57
  • In the Related Query Name section, is there a typo when you first put `School.objects.filter(student__name='abc')` shouldn't it be `students__name` since you defined the `related_name='students'` in the django example above? – 0x5929 Sep 03 '21 at 17:13
  • 1
    @Rennitbaby No, It should be `student__name` because we use `related_query_name` for filtering under queryset and in example `related_query_name` is `abc` – SHIVAM JINDAL Sep 09 '21 at 08:40