Jvn
Jvn

Reputation: 495

Django: Number the integer fields of the filtered queryset in order (efficiently)

It is possible to assign sequential numbers to the integer fields in the filtered queryset I am looking for by doing the following, but the query is issued every time I save(). How is it possible to save it?

queryset = Model.objects.filter(user=user)
for i, item in enumerate(queryset, start=1):
    item.index = i
    item.save()

Upvotes: 0

Views: 151

Answers (1)

Felix Eklöf
Felix Eklöf

Reputation: 3740

I don't understand your question completely, but if your problem is that it's issuing too many queries (one per .save()). Then you can use bulk_update

queryset = Model.objects.filter(user=user)
objs = []
for i, item in enumerate(queryset, start=1):
    item.index = i
    objs.append(item)
Model.objects.bulk_update(objs, ['index'])

Upvotes: 1

Related Questions