如何在Django中聚合一个查询集?

Rom*_*kov 4 django django-queryset

简短说明:给定一个查询集myQueryset,如何选择max("myfield")而不实际检索所有行并max在python中执行?

我能想到的最好的是max([r["myfield"] for r in myQueryset.values("myfield")]),如果有数百万行,那就不是很好.

详细说明:假设我的Django应用程序中有两个模型,City和Country.城市有国家的外键领域:

class Country(models.Model):
    name = models.CharField(max_length = 256)

class City(models.Model):
    name = models.CharField(max_length = 256)
    population = models.IntegerField()
    country = models.ForeignKey(Country, related_name = 'cities')
Run Code Online (Sandbox Code Playgroud)

这意味着Country实例.cities可用.假设我现在想为Country调用一种方法来highest_city_population返回最大城市的人口.来自LINQ背景,我的本能是尝试myCountry.cities.max('population')或类似的东西,但这是不可能的.

Dom*_*ger 7

使用聚合(Django 1.1中的新增功能).你这样使用它:

>>> from django.db.models import Max
>>> City.objects.all().aggregate(Max('population'))
{'population__max': 28025000}
Run Code Online (Sandbox Code Playgroud)

为了获得City每个人的最高人口Country,我认为你可以这样做:

>>> from django.db.models import Max
>>> Country.objects.annotate(highest_city_population = Max('city__population'))
Run Code Online (Sandbox Code Playgroud)