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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Field-argument distinct() keeps the first row per group, so the order_by that precedes it decides which row wins.
- 2The leading order_by column must match the distinct field, with secondary sort keys choosing the surviving row.
- 3distinct(*fields) is a PostgreSQL-only feature that pushes deduplication into the database instead of Python.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/distinct-on-queries-in-django-explained-python-f06d/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.