Skip to content

Retrieve related models with filters

Sometimes you need to retrieve related models with filters in Django ORM. Here is how you can do it.

from .models import Author, Book
from django.db.models import Prefetch, Count, Q
books = Book.objects.filter(title__icontains="Harry Potter")
authors = (Author.objects
.annotate(favorite_book_count=Count('book', filter=Q(book__in=books)))
.filter(favorite_book_count__gt=0)
.prefetch_related(Prefetch("book_set", queryset=books, to_attr="favorite_books")))

In the above code snippet, we are filtering the books with the title containing “Harry Potter”. Then we are annotating the authors that have books with the title containing “Harry Potter”. Finally, we are prefetching the related books for the authors with the title containing “Harry Potter”.