Skip to content
Django

ORM QuerySet

Filter, exclude, annotate and chain QuerySets.

By EZ4Code Team
ormquerysetfilter

Code

from myapp.models import Article

# Filter with lookups
published = Article.objects.filter(is_published=True)
recent = Article.objects.filter(views__gte=100)[:5]
exclude_drafts = Article.objects.exclude(is_published=False)

# Field lookups: __contains, __startswith, __in, __range
hits = Article.objects.filter(title__icontains="django")

# Ordering and distinct
ordered = Article.objects.order_by("-views", "title").distinct()

# Aggregation
from django.db.models import Count, Avg
stats = Article.objects.aggregate(total=Count("id"), avg_views=Avg("views"))

Explanation

QuerySets are lazy: filters build SQL only when evaluated. Double-underscore lookups like __gte, __icontains, and __in traverse fields and operators. Slicing with [:5] adds a LIMIT clause. aggregate() returns a dict of computed values across the whole queryset.

More Django Snippets