I need to make sure that an object that is being read from the database and written back cannot be changed in the meantime by another request / process.
Does transaction.atomic () provide this?
My tests don't tell me yet. If something is wrong with them, what would be the right way to achieve atomic READS and WRITES?
My example that I tested.
Put the Test class somewhere in your model. atomic_test.py and atomic_test2.py should be saved as control commands. Run python manage.py atomic_test first, then python manage.py atomic_test2. The second script is not blocked and its changes are lost.
models.py
class Test(models.Model): value = models.IntegerField()
atomic_test.py
from django.core.management.base import NoArgsCommand from django.db import transaction from time import sleep from core.models import Test class Command(NoArgsCommand): option_list = NoArgsCommand.option_list def handle(self, **options): Test.objects.all().delete() t = Test(value=50) t.save() print '1 started' with transaction.atomic(): t = Test.objects.all()[0] sleep(10) t.value = t.value + 10 t.save() print '1 finished: %s' %Test.objects.all()[0].value
atomic_test2.py
from django.core.management.base import NoArgsCommand from django.db import transaction from time import sleep from core.models import Test class Command(NoArgsCommand): option_list = NoArgsCommand.option_list def handle(self, **options): print '2 started' with transaction.atomic(): t = Test.objects.all()[0] t.value = t.value - 20 t.save() print '2 finished: %s' %Test.objects.all()[0].value
source share