Lmex89
Lmex89

Reputation: 37

Update a Queryset in Django instead of For loop

I am trying to update a queryset, I would like to calculate a Field order

class Temporal(model.Models):
   id = models.UUIDField(default=uuid.uuid4, primary_key=True)
   name=models.CharField(max_length=60)
   created_at = models.DateTimeField(auto_now_add=True)
   order = models.IntegerField(null=True, blank=True)

in my app it is important to order_by created_at, and then assing a order as index, everytime a new object is created assing value cero and the rest of the objects the need to be plus +1, but I would like to do using queryset instead of using a for loop :

items = Temporal.objects.all().order_by('-created_at')
for index, item enumerate(items):
   item.order=index + 1
   item.save()

assuming thousands of items on the database this would be very slow... thanks in advance

Upvotes: 0

Views: 997

Answers (1)

allexiusw
allexiusw

Reputation: 1743

According to the django documentation you can use bulk_update so checkout the link: https://docs.djangoproject.com/en/3.2/ref/models/querysets/#bulk-update

Try something like the following:

items = Temporal.objects.all().order_by('-created_at')
for index, item enumerate(items):
   item.order=index + 1
Temporal.objects.bulk_update(items, ['order'])

That's it.

Upvotes: 1

Related Questions