[Answered ]-Django Cannot update a query once a slice has been taken

0👍

You can update objects by their primary keys:

base_qs = Message.objects.filter(status="Unsent", sender=user, batch=batch).exclude(recipient_number__exact='')
total = base_qs.count()

for i in xrange(0, total, 500):
    page = list(base_qs[i:i+500])
    page_ids = [o.pk for o in page]
    # Do some stuff here
    base_qs.filter(pk__in=page_ids).update(send_date=datetime.datetime.now(), billed=True)

2👍

Use django database transactions for best performance:

https://docs.djangoproject.com/en/1.5/topics/db/transactions/

eg:

from django.db import transaction

total = Message.objects.filter(status="Unsent", sender=user, batch=batch).exclude(recipient_number__exact='').count()

    for i in xrange(0,total,500):
        message_batch = Message.objects.filter(status="Unsent").exclude(recipient_number__exact='')[i:i+500]
        # do some stuff here
        #once all done update the objects
        message_batch.update(send_date=datetime.datetime.now(), billed=True)

        with transaction.commit_on_success():
            for m in message_batch:
                m.update(send_date=datetime.datetime.now(), billed=True)                    

This will wrap eg. 5000 rows update in to one call to database instead of calling to database for 5000 times if you execute update not in a transaction.

Leave a comment