使用条件注释在Django 1.8中使用最新相关的值进行注释 [英] Annotate with value of latest related in Django 1.8 using conditional annotation
问题描述
我有以下型号:
class City(models.Model):
...
class Census(models.Model):
city = models.ForeignKey(City)
date = models.DateTimeField()
value = models.BigIntegerField()
现在我想用最新的人口普查值来标注城市查询。我如何实现?
Now I'd like to annotate a City-queryset with the value of the latest Census. How do I achieve that?
我尝试过:
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)
赞赏!
推荐答案
我也遇到一个需要相关集的最大值对象的问题,但我需要整个对象。我无法找出使用注释和案例的解决方案。直到我这样做,我使用这个预取解决方案。如果每个城市没有大量的人口普查对象,或者如果您的申请没有履行约束力,这可能适用于您。
I've also been having an issue where I need a max value object of a related set, but I require the entire object. I have not been able to figure out a solution using annotation and Case. Until I do, I use this prefetching solution. If each city does not have a large amount of census objects, or if your application is not performance bound, this may work for you.
inner_qs = Census.objects.order_by('-date')
cities = City.objects.prefetch_related(Prefetch("census_set", queryset=inner_qs, to_attr="census_list"))
class City(models.Model):
@property
def latest_census(self):
if hasattr(self, 'census_list') and len(self.census_list) > 0:
return self.census_list[0]
return None
如果不适合你,请考虑以下一些建议:
http://blog.roseman.org.uk/2010/08/14/getting-related-item-aggregate/
If this does not work for you, consider some of the suggestions found here: http://blog.roseman.org.uk/2010/08/14/getting-related-item-aggregate/
这篇关于使用条件注释在Django 1.8中使用最新相关的值进行注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!