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?

Asked By: pistacchio

||

Answers:

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

Image.objects.all().order_by("-id")[0]
Answered By: Daniel Roseman

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

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

Answered By: Raz

Your logic is right, this will return the max id

res = Image.objects.filter().aggregate(max_id=Max('pk'))
res.get('max_id')
Answered By: Mario César

I know this already has a right answer but here it’s another way of doing it:

prev = Image.objects.last()

This gives you the last object.

Answered By: patricia

Latest object without catching exception and using django orm:

Image.objects.filter().order_by('id').first()

Answered By: Krzysztof Dziuba

this also work perfectly:

max_id = Image.objects.values('id').order_by('-id').first()

This worked for me

[model].objects.last().id

Image.objects.last().id
Answered By: Uday Kiran
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.