python 32 lines · 7 steps

DISTINCT ON queries in Django

Three Django querysets use PostgreSQL's distinct-on-a-field to collapse rows down to one per group.

Explained by highlit
1from django.db.models import Q
2 
3from .models import Order
4 
5 
6def latest_orders_per_customer(status="paid"):
7 return (
8 Order.objects.filter(status=status)
9 .exclude(customer__isnull=True)
10 .order_by("customer_id", "-created_at")
11 .distinct("customer_id")
12 )
13 
14 
15def unique_shipping_regions(warehouse):
16 return (
17 Order.objects.filter(warehouse=warehouse)
18 .order_by("shipping_region")
19 .distinct("shipping_region")
20 .values_list("shipping_region", flat=True)
21 )
22 
23 
24def most_recent_touch_per_product(campaign):
25 return (
26 Order.objects.filter(
27 Q(campaign=campaign) | Q(referral__campaign=campaign)
28 )
29 .select_related("product", "customer")
30 .order_by("product_id", "-updated_at")
31 .distinct("product_id")
32 )
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Field-argument distinct() keeps the first row per group, so the order_by that precedes it decides which row wins.
  2. 2The leading order_by column must match the distinct field, with secondary sort keys choosing the surviving row.
  3. 3distinct(*fields) is a PostgreSQL-only feature that pushes deduplication into the database instead of Python.

Related explainers

Share this explainer

Here's the card — post it anywhere.

DISTINCT ON queries in Django — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code