what is related_name and related_query_name in django?

青春壹個敷衍的年華 提交于 2020-06-17 00:13:11

问题


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='+'


回答1:


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/



来源:https://stackoverflow.com/questions/60119027/what-is-related-name-and-related-query-name-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!