Reverse Relationships
In Django, you can define reverse relationships to access related objects from the reverse side of a ForeignKey or ManyToManyField relationship. Let's create a simple example using the Author
and Book
models to demonstrate reverse relationships.
1. Create the Author
and Book
models:
In this example:
We have two models:
Author
andBook
.Each
Book
has a foreign key relationship with anAuthor
, meaning each book is authored by a specific author.
2. Create and retrieve Author and Book objects:
In this code:
We create two authors,
J.K. Rowling
andGeorge Orwell
, and three books associated with these authors.To access the books written by a specific author (in this case, J.K. Rowling), we use the
book_set
attribute, which is automatically generated by Django for the reverse relationship fromAuthor
toBook
.We then loop through the books written by J.K. Rowling and print their titles.
The book_set
attribute allows you to access the related Book
objects for a specific Author
. You can also define a related_name
on the ForeignKey to provide a custom name for the reverse relationship if you prefer not to use the default modelname_set
.
Last updated