1👍
✅
First, to answer your questions:
-
If the exception bubbles up and out of the
with
statement (which looking at your code it will), then yes, the the transaction will get rolled back. -
Yes, when a transaction is rolled back, everything that has happened so far will be undone.
By the way, you should use signals for automatically updating such count fields so you never have to worry about forgetting to call the method manually (and as before, this will be covered by the transaction if run inside one). And you get the added benefit of it working when objects are deleted.
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.db import transaction
@receiver(post_save, sender=Book)
@receiver(post_delete, sender=Book)
@transaction.atomic
def _update_count(sender, instance, using, **kwargs):
# get total number of books with this category
count = Book.objects.filter(category=instance.category).count()
# update the denormalized data
BookConfig.objects.filter(key=instance.category).update(count=count)
Source:stackexchange.com