Reputation: 2495
I have a model Foo
in my models.py like this:
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)
I want to get the max quantity
from the table. How can I get that?
Upvotes: 6
Views: 6754
Reputation: 7434
Use Django Aggregations:
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')
Upvotes: 11
Reputation: 1394
You can do like this for your solution...
from django.db.models import Max
Foo.objects.all().aggregate(Max('quantity'))['quantity__max']
Upvotes: 4