Search code examples
pythondjangotransactionsatomic

Understanding atomic transactions in Django


I'm trying to update two IntegerField's in django 1.8.4 so I've decided to use atomic transactions, but I have some doubts:

1- Is that good idea to use atomic transactions in this case? What is the real benefit of using it? How much more efficient is it?

2- How can I check if these two pieces work same as each other or not?

A.

@transaction.atomic
class LinkManager(models.Manager):
    def vote_up(self, pk, increment=True):
        if increment:
            <update field 1, incrementing by 1>
        else:
            <update field 1, decrementing by 1>

B.

 class LinkManager(models.Manager):
        def vote_up(self, pk, increment=True):
            if increment:
                with transaction.atomic():
                    <update field 1, incrementing by 1>
            else:
                with transaction.atomic():
                    <update field 1, decrementing by 1>

Solution

  • Is it a good idea to use atomic transactions in this case?

    No, the atomic decorator makes sure that either all or no updates will be executed in the transactions. It's probably completely useless in this case.

    What's the benefit of atomic?

    Assuming you're updating a few models from a form, the atomic decorator will ensure that either all models get updated, or if there's an error. None at all.

    Is it more efficient?

    No, absolutely not. It's a data safety thing, it's actually less efficient and slower than a regular update as it needs to create a transaction for every block.

    How can it work?

    Update within the database, instead of fetching the result and writing it back just let the database increment it for you.

    Something like this:

    from django.db.models import F
    SomeModel.objects.filter(pk=123).update(some_field=F('some_field') + 1)