Django:获取最新的不同对象

标签 django django-orm

假设我有一个 WeatherReport 对象,其中包含字段 datetemperaturecity

我想获取每个城市的所有最新 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/

相关文章:

python - Django:在没有 javascript 的情况下添加内联表单集行

python - 在 Django 中有效地获取相关模型的数量

python - 实现电子书 Paypal 购物的最简单方法

python - Django 1.9 无法修改 unique_together (ValueError) 错误的约束数

python - django 重置内容类型不匹配

python - Django 在查询中打破长查找名称

带有计数注释的 django admin list_display

python - 在 Django 中使用具有相同值的不同模型字段

django - 用 bool 值注释查询集,其中一个字段等于或不等于另一个字段

python - 将 django View 转换为 django Rest Framework APIView