Get the latest order of each customer, without N+1.
1 2 3 4 5 6 7 8 9 10 11 12 | # ====================================================================== # Q: Get the latest order of each customer, without N+1. # ====================================================================== latest = Order.objects.filter(customer=OuterRef('pk')).order_by('-created_at') customers = Customer.objects.annotate( last_order_at=Subquery(latest.values('created_at')[:1]), last_order_id=Subquery(latest.values('id')[:1]), ) # Alternatively in PostgreSQL: DISTINCT ON Order.objects.order_by('customer_id', '-created_at').distinct('customer_id') |