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.
- Category Performance & Optimization
- Total Views 403
- Last Modified 27 April, 2026
- Tags #performance #queries #count #optimization
Previous snippet
Bulk Update for Performance
Next snippet