Get the index of an element in a queryset

Deniz Dogan picture Deniz Dogan · Jun 25, 2009 · Viewed 41.3k times · Source

I have a QuerySet, let's call it qs, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let's call it obj. Now I'd like to know at what index obj has in qs, as efficiently as possible. I know that I could use .index() from Python or possibly loop through qs comparing each object to obj, but what is the best way to go about doing this? I'm looking for high performance and that's my only criteria.

Using Python 2.6.2 with Django 1.0.2 on Windows.

Answer

drdaeman picture drdaeman · Jun 25, 2009

Compact and probably the most efficient:

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