Rahul Sharma
Rahul Sharma

Reputation: 2495

Get maximum value of a field in django

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

Answers (2)

Horatiu Jeflea
Horatiu Jeflea

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

Manan M.
Manan M.

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

Related Questions