Get the index of an element in a queryset

If you’re already iterating over the queryset and just want to know the index of the element you’re currently on, the compact and probably the most efficient solution is:

for index, item in enumerate(your_queryset):
    ...

However, don’t use this if you have a queryset and an object obtained by some unrelated means, and want to learn the position of this object in the queryset (if it’s even there).

Leave a Comment