4

簡単な説明: queryset が与えられた場合、実際にすべての行を取得してPythonで実行せずにmyQueryset選択するにはどうすればよいですか?max("myfield")max

私が考えることができる最高のものはmax([r["myfield"] for r in myQueryset.values("myfield")])、何百万行もある場合はあまり良くありません。

詳細な説明: Django アプリに City と Country の 2 つのモデルがあるとします。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利用可能であることを意味します。highest_city_populationここで、最大都市の人口を返すCountry のメソッドを書きたいとしましょう。LINQ のバックグラウンドを持っているため、私の自然な本能は試してみるmyCountry.cities.max('population')ことですが、これは不可能です。

4

1 に答える 1

7

集計を使用します(Django 1.1 の新機能)。次のように使用します。

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

Cityfor eachの最大人口を取得するには、次のCountryようなことができると思います。

>>> from django.db.models import Max
>>> Country.objects.annotate(highest_city_population = Max('city__population'))
于 2010-01-18T16:58:04.843 に答える