我有以下型号:
class City(models.Model):
...
class Census(models.Model):
city = models.ForeignKey(City)
date = models.DateTimeField()
value = models.BigIntegerField()
Run Code Online (Sandbox Code Playgroud)
现在我想用最新的人口普查值来注释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)
Run Code Online (Sandbox Code Playgroud)
任何帮助非常感谢!