假设我有一个 WeatherReport
对象,其中包含字段 date
、temperature
和 city
。
我想获取每个城市的所有最新 WeatherReport
对象。我想我会做类似的事情
WeatherReport.objects.order_by('-date').distinct('city')
但这失败了,返回错误
ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
最佳答案
这应该有效。当我遇到这个问题时,它对我有用。
WeatherReport.objects.order_by('city', '-date').distinct('city')
似乎 DISTINCT ON
表达式必须匹配最左边的 ORDER BY
表达式。因此,通过将您在 distinct
中使用的列作为 order_by
中的第一列,我认为它应该有效。
关于Django:获取最新的不同对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20766366/