2010-01-18 143 views
4

簡短說明:給定查詢集myQueryset,我如何選擇max("myfield")而不實際檢索所有行,並在Python中做max如何在Django中的單個查詢集上進行聚合?

我能想到的最好的是max([r["myfield"] for r in myQueryset.values("myfield")]),如果有數百萬行,這不是很好。

長描述:假設我的Django應用程序中有兩個模型,城市和國家。市有一個外鍵字段國家:

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') 

這意味着一個國家實例有.cities可用。假設我現在想寫一個名爲highest_city_population的國家的方法,返回最大城市的人口。從LINQ背景來看,我的天生本能是嘗試myCountry.cities.max('population')或類似的東西,但這是不可能的。

回答

7

使用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')) 
+0

D'哦!謝謝!不知何故,我所有的嘗試都發現了這個問題,不斷地打'annotate',這不太合適......(看起來像更長問題的答案,因此是'myCountry.cities.aggregate(maxpop = Max('population'))[ 'maxpop'])' – 2010-01-18 17:02:04

+0

@romkyns - 你能測試我答案的後半部分嗎?我對聚合有點新,但我認爲(從閱讀文檔),這是它的工作原理。讓我知道如果不是,我會編輯我的答案。 – 2010-01-18 17:03:52

+0

@ [多米尼克羅傑]測試我自己的版本(見上面的評論)靈感來自你的答案 - 它確實是我需要的。你使用'annotate'的例子並不完全是我想要的 - 我需要這個價值爲一個特定的國家,而不是所有的國家。 – 2010-01-18 17:10:35

相關問題