Optimize QuerySets with exists()

A snippet showing how to use exists() to optimize queries.


# views.py

from .models import Order

def has_pending_orders(request):
    # Check efficiently for pending orders without loading them into memory
    if Order.objects.filter(status="PENDING").exists():
        return HttpResponse("There are pending orders.")
    else:
        return HttpResponse("No pending orders.")
      
Explanation:
  • .exists() uses a cheap SELECT 1 LIMIT 1 query instead of loading rows into memory.
  • .exists() is much faster than len when you need to check if a queryset is empty.
Previous snippet
Database Connection Pooling
Next snippet
Use Cached Sessions
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.