Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get penultimate item from QuerySet in Django?

How to get the penultimate item from Django QuerySet? I tried my_queryset[-2] (after checking whether the my_queryset length is greater than 1) as follows:

if len(my_queryset)>1:
     query = my_queryset[-2]

and it returns:

Exception Value: Negative indexing is not supported.

Is there some "Django" way to get such item?

The only thing which comes to my mind is to reverse the queryset and get my_queryset[2] but I'm not sure about its efficiency.

EDIT:

scans = self.scans.all().order_by('datetime')
if len(scans)>1:
    scan = scans[-2]
like image 776
Milano Avatar asked Dec 07 '25 19:12

Milano


1 Answers

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:

like image 69
e4c5 Avatar answered Dec 09 '25 12:12

e4c5