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

2023-12-27

简短的介绍:给定一个查询集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')

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


Use 聚合 http://docs.djangoproject.com/en/dev/topics/db/aggregation/(Django 1.1 中的新功能)。你像这样使用它:

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

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

>>> from django.db.models import Max
>>> Country.objects.annotate(highest_city_population = Max('city__population'))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Django 中聚合单个查询集? 的相关文章

随机推荐