Skip to content
Django

ORM QuerySet

Filter, exclude, annotate and chain QuerySets.

#orm#queryset#filter

Code

django
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"))