How to Use Subquery() in Django With Practical Examples

PHOTO EMBED

Mon Apr 01 2024 05:59:22 GMT+0000 (Coordinated Universal Time)

Saved by @viperthapa

from django.db.models import Count

# Using Subquery
authors_with_book_count = Author.objects.annotate(book_count=Subquery(Book.objects.filter(author=OuterRef('pk')).values('author').annotate(count=Count('id')).values('count')))

# Equivalent Non-Subquery Approach
authors = Author.objects.all()
authors_with_book_count = []
for author in authors:
    book_count = Book.objects.filter(author=author).count()
    authors_with_book_count.append({'author': author, 'book_count': book_count})
Copy
content_copyCOPY

https://djangocentral.com/how-to-use-subquery-in-django/