[Fixed]-2nd latest object through django shell is there any query?

1👍

You can use order_by on the id of the objects in reverse:

# order by lateness in descending oerder
models_desc = ModelName.objects.order_by('-id')

#last two objects
last_two = models_desc[0:1]

# 2nd latest
second_latest = models_desc[1]

0👍

Not sure why you don’t want indexing, it would be pretty simple

ModelName.objects.order_by('-id')[1]

Otherwise you could fetch the last one and subtract one from it’s id value, to get the previous objects

ModelName.objects.get(ModelName.objects.latest('id').id - 1)

For both, you will need to wrap it into a try-catch block.

👤C14L

Leave a comment