📝 Django

related_name in Django

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
82
🌿
Level
Medium

related_name is the name used for reverse access from a related model back to its parent.

class Task(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
# Reverse access — Django auto-generates the name: <model>_set
project = Project.objects.get(pk=1)
project.task_set.all()  # all tasks for the project
class Task(models.Model):
    project = models.ForeignKey(
        Project,
        on_delete=models.CASCADE,
        related_name='tasks',  # project.tasks instead of project.task_set
    )
project.tasks.all()
project.tasks.filter(status='done')
project.tasks.count()

Example with Multiple ForeignKeys to the Same Model

class Task(models.Model):
    owner = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='owned_tasks',    # user.owned_tasks.all()
    )
    assignee = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='assigned_tasks', # user.assigned_tasks.all()
    )

Without related_name Django will raise an error: name clash.

created_by = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
    related_name='+',  # no reverse access
)

In a Template

{% for task in project.tasks.all %}
  <li>{{ task.title }}</li>
{% endfor %}

In a DRF Serializer

class ProjectSerializer(serializers.ModelSerializer):
    tasks = TaskSerializer(many=True, read_only=True)  # via related_name

    class Meta:
        model = Project
        fields = ['id', 'name', 'tasks']

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 138
📝

Django: Template Tags

Template tags are logic inside HTML. Unlike {{ variable }} which only outputs a value,...

📅 30.06.2026 👁️ 89
📝

Django: Static Files

Static files are CSS, JavaScript, images, and fonts. Django handles them in a specific way:...

📅 30.06.2026 👁️ 79

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!