[Fixed]-How to avoid/fix django's DatabaseTransactionError

1👍

The Django docs on controlling transactions explicitly have an example of catching exceptions in atomic blocks.

In your case, you don’t appear to be using the atomic decorator at all, so first you need to add the required import.

from django.db import transaction

Then you need to move the code that could raise a database error into an atomic block:

try:
    with transaction.atomic():
        cached_calculation.save()
    return cached_calculation
# if another thread beat you to saving this, catch the exception
# but return the object that was just calculated
except DatabaseError as error:
    log(error)
    return cached_calculation

Leave a comment