Django select max id


Question

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?

1
24
5/21/2010 6:19:00 PM

Accepted Answer

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

Image.objects.all().order_by("-id")[0]
39
5/21/2010 7:28:59 PM

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

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon