Django:获取最新的不同对象

mas*_*rre 2 django django-orm

假设我有一个WeatherReport与领域对象datetemperaturecity

我想获取WeatherReport每个城市的所有最新对象。我想我会做类似的事情

WeatherReport.objects.order_by('-date').distinct('city')
Run Code Online (Sandbox Code Playgroud)

但这失败了,返回错误

ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
Run Code Online (Sandbox Code Playgroud)

小智 6

这应该有效。当我遇到这个问题时,它对我有用。

WeatherReport.objects.order_by('city', '-date').distinct('city')
Run Code Online (Sandbox Code Playgroud)

似乎DISTINCT ON表达式必须匹配最左边的ORDER BY表达式。因此,通过将您使用的列distinct作为 中的第一列order_by,我认为它应该可以工作。