[Django]-How to get penultimate item from QuerySet in Django?

6👍

This code which produces an error

scans = self.scans.all().order_by('datetime')
if len(scans)>1:
    scan = scans[-2]

Is the equivalent of

scans = self.scans.all().order_by('-datetime')
if len(scans)>1:
    scan = scans[1]

If you want to get the second one the index to use is 1 and not 2 because in python offsets starts from 0.

Also note that django querysets are lazy which means you can change your mind about ordering without a performance hit provided that proper indexes are available.

QuerySets are lazy – the act of creating a QuerySet doesn’t involve
any database activity. You can stack filters together all day long,
and Django won’t actually run the query until the QuerySet is
evaluated. Take a look at this example:

👤e4c5

Leave a comment