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
Model Definition
Define a Django model with field types and meta options.
Class-Based Views
Use generic class-based views for common CRUD flows.
URL Routing
Wire URLs to views with path converters and includes.
ModelForms
Build forms from models with validation and widgets.
Template Tags
Use built-in tags and filters in Django templates.
Admin Customization
Customize the Django admin with list_display and actions.