ForeignKey missing related_name

ORM queries are more readable and relationships more explicit when related_name is specified.

The related_name attribute specifies the name of the reverse relation from the related model back to the model.

Django automatically creates a related_name if related_name is not set. Django uses the lower-case name of the model with the suffix _set.

So in practice, do this


class UniversityStudent(models.Model):
    grades = models.ForeignKey(
      Grade, related_name='students'
    )

for student in Grade.students.all():
  ...

Instead of this


class UniversityStudent(models.Model):
    grades = models.ForeignKey(Grade)

for student in Grade.universitystudent_set.all():
   ...

Are you affected? Check with
pip install django-doctor
.

Configuring this check

Django Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code missing-related-name in your pyproject.toml file.

Read more about configuring Django Doctor.