Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a do a "greatest-n-per-group" query in django?

(This is the django version of the thread at SQL join: selecting the last records in a one-to-many relationship)

Suppose I have a table of customers and a table of purchases. Each purchase belongs to one customer. I want to get a list of all customers along with their last purchase. Can it be done without raw SQL and without multiple database queries?

like image 573
netvope Avatar asked Jan 21 '10 17:01

netvope


2 Answers

You can't do this in one query in Django. You can get the customer with just the date of their most recent purchase like this:

from django.db.models import Max
customers = Customer.objects.annotate(Max('purchase__date'))

but you don't automatically get access to the actual purchase this way.

like image 191
Daniel Roseman Avatar answered Sep 27 '22 17:09

Daniel Roseman


You can take a look at similar discussion:

Django Query That Get Most Recent Objects From Different Categories

like image 36
Tomasz Zieliński Avatar answered Sep 27 '22 18:09

Tomasz Zieliński