liveBook · Manning

Related_name

As explained in Django in Action

related_name is a Django relationship-field option that sets the attribute name for traversing from a referenced object to related objects.

related_name controls the attribute Django adds to the referenced object for traversing a reverse relationship. Without it, a Venue reached through Room.venue exposes rooms as venue.room_set; related_name="my_rooms" changes that attribute to venue.my_rooms. section 4.7.1

Use the option deliberately:

  • Keep the default when it is clear; renaming without a good reason can confuse maintainers. section 4.7.1
  • Choose distinct names when a model has two ForeignKey relationships to the same target. section 4.7.1
  • Set related_name="+" to disable the reverse relationship when that is useful for efficiency. section 4.7.1

Naming a venue's rooms

With Room.venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name="my_rooms"), code can retrieve a venue's rooms with venue.my_rooms.all() instead of venue.room_set.all(). The manager supports the same kinds of queries as .objects, but limits results to related Room objects. section 4.7.1

Listing 4.13 Venue and Room models and their one-to-many relationship
# RiffMates/bands/models.py
...
class Venue(models.Model):
    name = models.CharField(max_length=20)

    def __str__(self):
        return f"Venue(id={self.id}, name={self.name})"


class Room(models.Model):
    name = models.CharField(max_length=20)
    venue = models.ForeignKey(Venue, on_delete=models.CASCADE)  #1

    def __str__(self):
        return f"Room(id={self.id}, name={self.name})"

Inspect the Venue and Room ForeignKey that creates the default reverse room_set manager. section 4.7.1

How Django in Action covers it

How deep it goes
Explains default and custom reverse managers, special cases, and related querying, but defers detailed documentation.
Examples
Demonstrates Venue and Room models, default room_set access, and a my_rooms replacement.
What it assumes
Assumes familiarity with Django models and ForeignKey fields.
What you can do after
Apply related_name to choose readable reverse attributes and avoid collisions between multiple ForeignKey relationships.
How it connects
Connects ForeignKey relationships with reverse relationships, related_query_name, one-to-many relationships, and field lookups.

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.