Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django select max id

Tags:

python

django

given a standard model (called Image) with an autoset 'id', how do I get the max id?

So far I've tried:

max_id = Image.objects.all().aggregate(Max('id'))

but I get a 'id__max' Key error.

Trying

max_id = Image.objects.order_by('id')[0].id

gives a 'argument 2 to map() must support iteration' exception

Any help?

like image 437
pistacchio Avatar asked May 21 '10 18:05

pistacchio


2 Answers

In current version of django (1.4) it is even more readable

Image.objects.latest('id').id

like image 179
Raz Avatar answered Nov 07 '22 05:11

Raz


Just order by reverse id, and take the top one.

Image.objects.all().order_by("-id")[0]
like image 49
Daniel Roseman Avatar answered Nov 07 '22 07:11

Daniel Roseman