如何通过Django中的单个查询器进行聚合? [英] How to aggregate over a single queryset in Django?

查看:145
本文介绍了如何通过Django中的单个查询器进行聚合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短描述:给定一个查询器 myQueryset ,如何选择 max(myfield)没有实际检索所有行,并在python中执行 max



我能想到的最好的是 max([r [myfield] for r in myQueryset.values(myfield)]),如果有数百万行,这不是很好。 / p>

长描述:说我的Django应用程序,城市和国家中有两个模型。城市有一个国家的外键字段:

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

class城市(models.Model):
name = models.CharField(max_length = 256)
population = models.IntegerField()
country = models.ForeignKey(Country,related_name ='cities')

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

解决方案

使用聚合(Django 1.1中的新增)。你这样使用:

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

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

 >>>从django.db.models import Max 
>>> Country.objects.annotate(highest_city_population = Max('city__population'))


Short description: given a queryset myQueryset, how do I select max("myfield") without actually retrieving all rows and doing max in python?

The best I can think of is max([r["myfield"] for r in myQueryset.values("myfield")]), which isn't very good if there are millions of rows.

Long description: Say I have two models in my Django app, City and Country. City has a foreign key field to 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')

This means that a Country instance has .cities available. Let's say I now want to write a method for Country called highest_city_population that returns the population of the largest city. Coming from a LINQ background, my natural instinct is to try myCountry.cities.max('population') or something like that, but this isn't possible.

解决方案

Use Aggregation (new in Django 1.1). You use it like this:

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

To get the highest population of a City for each Country, I think you could do something like this:

>>> from django.db.models import Max
>>> Country.objects.annotate(highest_city_population = Max('city__population'))

这篇关于如何通过Django中的单个查询器进行聚合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆