About Backward Relations

Django model relations have an attribute related_name. It defines how instances of this model can be accessed from the instances of the related model. The default value is "mymodel_set".

Custom related_name attributes are mandatory, when two models have more than one relation between each other, for example, a location can be a venue or an organizer of an event.

By default, related_name works as a manager on the related model and as a lookup in the queries. But it's possible to customize the lookup name for queries using the related_query_name attribute.

For example, the User model has the field groups defined as:

1
2
3
4
5
6
    groups = models.ManyToManyField(
        Group,
        # ...
        related_name="user_set",
        related_query_name="user",
    )

This means that you would access the users of the group as follows:

1
>>> group.user_set.all()

But you would query the users of a group this way:

1
>>> Group.objects.filter(user=request.user)

Tips and Tricks Programming Django 4.x Django 3.2 Django 2.2