Reputation: 891
Supposing I have a WeatherReport
object with fields date
, temperature
, and city
.
I want to get all the most recent WeatherReport
objects for each city. I think I would do something like
WeatherReport.objects.order_by('-date').distinct('city')
But this fails, returning the error
ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
Upvotes: 2
Views: 1632
Reputation:
This should work. It worked with me when I came across this problem.
WeatherReport.objects.order_by('city', '-date').distinct('city')
It seems that the DISTINCT ON
expression(s) must match the leftmost ORDER BY
expression(s). So by making the column you use in distinct
as the first column in the order_by
, I think it should work.
Upvotes: 8