Loading skill
Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Moves Django Python-side loops for counts, sums, flags, and rankings into database-side annotations, Subquery, and Window expressions.
82% 95%+14 ptsof test cases passed
Passed 21 of 22 test cases with the skill, and 18 of 22 without it.
3 of 3 safety checks passed
Not used yet
from django.db.models import Count, Q, Sum
accounts = Account.objects.annotate(
open_order_count=Count("orders", filter=Q(orders__status="open")),
open_order_total=Sum("orders__total_cents", filter=Q(orders__status="open"), default=0),
)
Use filtered aggregates when multiple conditional counts or sums are needed from the same relationship.
Exists() For Boolean Flagsfrom django.db.models import Exists, OuterRef
recent_orders = Order.objects.filter(
account_id=OuterRef("pk"),
created_at__gte=cutoff,
)
accounts = Account.objects.annotate(has_recent_orders=Exists(recent_orders))
Exists() can be more efficient than counting when all you need is yes/no.
Subquery() For Latest Related Valuefrom django.db.models import OuterRef, Subquery
latest_order = (
Order.objects
.filter(account_id=OuterRef("pk"))
.order_by("-created_at")
)
Next to this one in the catalogue, plus more from the same author.