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

Time:10-22

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()

CodePudding user response:

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'])
  • Related