Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get max value in django ORM

>>> AuthorizedEmail.objects.filter(group=group).values('added')
[{'added': datetime.datetime(2012, 5, 19, 13, 8, 7)}, 
{'added': datetime.datetime(2012, 5, 19, 13, 8, 7)}, 
{'added': datetime.datetime(2012, 5, 19, 13, 7, 23)}, 
{'added': datetime.datetime(2012, 5, 19, 13, 8, 7)}]

What would be the best way to get the max value here? In python or in the ORM?

like image 720
David542 Avatar asked May 19 '12 20:05

David542


3 Answers

latest returns the latest object in the table according to the added date:

AuthorizedEmail.objects.filter(group=group).latest('added')
like image 180
gypaetus Avatar answered Nov 18 '22 06:11

gypaetus


From the documentation:

>>> from django.db.models import Max
>>> AuthorizedEmail.objects.aggregate(Max('added'))

And to fetch the value in the template:

{{ item.added__max }}
like image 31
David542 Avatar answered Nov 18 '22 07:11

David542


AuthorizedEmail.objects.filter(group=group).order_by('-added')[0]
like image 5
Burhan Khalid Avatar answered Nov 18 '22 06:11

Burhan Khalid