Mongoengine, how to get last element in listField

1.5k views Asked by At

The familiar pythonic slicing conventions of myList[-1:][0] and myList[-1] are not available for Mongoengine listFields because it does not support negative indices. Is there an elegant way to get the last element of a list?

Error verbiage for posterity:

IndexError: Cursor instances do not support negative indices

2

There are 2 answers

0
rowend On BEST ANSWER

You can access the last item with this code:

myList[len(myList) - 1]
0
GoBear On

Do not use len on a QuerySet, because this will evaluate the query set. Django docs:

A QuerySet is evaluated when you call len() on it. This, as you might expect, returns the length of the result list.

If you just want to get the length of the set use count instead. So answering your question, I would use something like myList[myList.count() - 1].