I need to loop through a queryset and put the objects into a dictionary along with the sequence number, i, in which they appear in the queryset. However a Python for loop doesn't seem to provide a sequence number. Therefore I've had to create my own variable i and increment it with each loop. I've done something similar to this, is this the cleanest solution?
ledgers = Ledger.objects.all()
i = 0
for ledger in ledgers:
print('Ledger no ' str(i) ' is ' ledger.name)
i = 1
CodePudding user response:
enumerate(…) [Python-doc] is designed for that:
ledgers = Ledger.objects.all()
for i, ledger in enumerate(ledgers):
print(f'Ledger no {i} is {ledger.name}')
CodePudding user response:
You can annotate the index like that:
from django.db.models import Window, F
ledgers = Ledger.objects.annotate(index=Window(expression=DenseRank(), order_by=F('id').desc()))
ledgers_dict = dict(ledgers.values_list('index', 'name'))
ledgers.filter(index__lt=5, name__contains='foo') # ledgers is a queryset
With that you get a queryset that you can use for further database operations.
