Querying
Master Ryx's powerful QuerySet API for filtering, ordering, and aggregating data.
What You'll Learn
- Filtering — Lookups, comparisons, string matching
- Q Objects — OR, NOT, and complex boolean expressions
- Ordering & Pagination — Sort, limit, offset, slice
- Aggregations — Count, Sum, Avg, Min, Max
- Values & Annotate — GROUP BY patterns and extra fields
Quick Reference
# Filter
Post.objects.filter(active=True, views__gte=100)
# Q objects (OR / NOT)
Post.objects.filter(Q(active=True) | Q(views__gte=1000))
# Chain
Post.objects.filter(active=True).order_by("-views").limit(10).offset(20)
# Aggregate
Post.objects.aggregate(total=Count("id"), avg=Avg("views"))
# Annotate (GROUP BY)
Post.objects.values("author_id").annotate(count=Count("id"))