相关疑难解决方法(0)

使用条件注释在Django 1.8中使用最新相关值进行注释

我有以下型号:

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)

任何帮助非常感谢!

django django-orm django-queryset django-1.8

28
推荐指数
2
解决办法
3300
查看次数

标签 统计

django ×1

django-1.8 ×1

django-orm ×1

django-queryset ×1