How do I enumerate rows returned in Django?

Viewed 547

Similar to how Python's enumerate() works, I'd like to assign each row returned a unique increasing integer. (Not the row id, but rather the row number in the results!)

i.e.,

for p in models.People.objects.all().values('N', 'name'):
   print p['N'], p['name']

with output of...

0 Mary
1 John
2 Nikita
3 Fred

In this particular case, I want to do this on the SQL backend and not simply wrap enumerate() around the query results.

I would also not expect the enumerations to be stable across queries where the data has changed.

1 Answers

This can be done with annotate in Django 1.x:

from django.db.models.expressions import RawSQL                                 

qry = models.People.objects.all().\
    annotate(N=RawSQL('row_number() over ()', [])).\
    values('N', 'name')
for p in qry:
    print p['N'], p['name']

In Django 2.0 this can be done with a Window expression using RowNumber.

Related