๐Ÿ“ Django

related_name in Django

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
294
๐ŸŒฟ
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

๐Ÿ“

Search in Django

You can start with simple Django ORM filters and move to PostgreSQL features when you...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 280
๐Ÿ“

Swagger Documentation with drf-spectacular

drf-spectacular generates an OpenAPI 3.0 schema and Swagger UI for DRF.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 566
๐Ÿ“

settings.py: Django Configuration

settings.py is the central configuration file for a Django project.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 316

Did you like the article?

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