获取django中某个字段的最大值

Rah*_*rma 6 python django

我的 models.py 中有一个模型,Foo如下所示:

class Foo(models.Model):

    transaction_no = models.IntegerField(default=0, blank=True, null=True)
    transaction_date = models.DateField(default=datetime.now)
    quantity = models.IntegerField(default=0, blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)

quantity我想从表中获取最大值。我怎样才能得到它?

Hor*_*lea 10

使用 Django聚合

from django.db.models import Max

Foo.objects.all().aggregate(Max('quantity'))

# or 

Foo.objects.aggregate(Max('quantity'))

# or ignore empty quantities

Foo.objects.filter(quantity__isnull=False).aggregate(Max('quantity'))

# how to get the max value

max_quantity = Foo.objects.aggregate(Max('quantity')).get('quantity__max')
Run Code Online (Sandbox Code Playgroud)