Optimize Query Counts with count()

A snippet showing how to use count() optimally in Django queries.


# views.py

from .models import Comment
from django.http import HttpResponse
def comment_count(request, post_id):
    total = Comment.objects.filter(post_id=post_id).count()  # SELECT COUNT(*)
    return HttpResponse(f"Total comments: {total}")
      
Explanation:
  • count uses a cheap COUNT(*) query instead of loading objects into memory.
  • count is much faster than len when you need to count many rows.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.