I think you mean one transaction in the transaction manager, not one transaction per iteration.
I believe the loop design is great, but you need to manage the transaction manager.
First you need to use the Django transaction manager, which you can read about here:
https://docs.djangoproject.com/en/dev/topics/db/transactions/
You will need to add this line to your middleware_classes in settings.py
'django.middleware.transaction.TransactionMiddleware',
Then you will need to import the transaction, wherever you are,
from django.db import transaction
Put your loop in a function and add a decorator, for example:
@transaction.commit_on_success def my_function(): i = 1 for p in Photo.objects.order_by("-current_rating"): p.current_rank = i p.save() i += 1
Now, when this function is called, it will have only one transaction, not N. If this fails, the transaction will be rolled back.
You can also use commit_manually. See the docs above for more details.
source share