Retrieve related models
models.py
from django.db import models
class Author(models.Model): name = models.CharField(max_length=100)
def __str__(self): return self.name
class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='book_set')
def __str__(self): return self.title
Retrieve related models
Here is how you can retrieve related models in Django ORM.
from myapp.models import Author, Book
famous_author = Author.objects.get(name='J.K. Rowling')famous_books = famous_author.book_set.all()
this will execute the 2 queries to get the author and the books related to the author
Prefetch related models
If you want to reduce the number of queries you can use the prefetch_related
method
from myapp.models import Author, Book
famous_author = Author.objects.prefetch_related('book_set').get(name='J.K. Rowling')famous_books = famous_author.book_set.all()