【发布时间】:2015-09-22 22:51:36
【问题描述】:
我有以下型号:
class City(models.Model):
...
class Census(models.Model):
city = models.ForeignKey(City)
date = models.DateTimeField()
value = models.BigIntegerField()
现在我想用最新人口普查的值来注释 City-queryset。我如何做到这一点?
我试过了:
City.objects.annotate(population=Max('census__date'))
# --> annotates date and not value
City.objects.annotate(population=Max('census__value'))
# --> annotates highest value, not latest
City.objects.annotate(population=
Case(
When(
census__date=Max('census__date'),
then='census__value')
)
)
# --> annotates 'None'
City.objects.annotate(population=
Case(
When(
census__date=Max('census__date'),
then='census__value')
), output_field=BigIntegerField()
)
# --> takes forever (not sure what happens at the end, after some minutes I stopped waiting)
非常感谢任何帮助!
【问题讨论】:
-
1) 性能很重要还是只是离线的零星报告? 2) 是否应该与数据库品牌无关?
-
1) 是的,性能很重要,不过为了美观,一些性能妥协是可以接受的。 2) 是的,至少应该适用于 MySQL 和 PostgreSQL。
-
较新的 Django 版本 (>1.8) 解决方案:stackoverflow.com/questions/43775102/…
标签: django django-queryset django-orm django-1.8