Django: write something to the database in a catch block, when using an atomic transaction
I have a Django REST Framework serializer which uses select_for_update in combination with atomic transitions, like this: https://docs.djangoproject.com/en/4.2/ref/models/querysets/#select-for-update/. That works fine, except that I want to write something to the database when an error is thrown... and these insert statements are getting rolled back, never making it to the database.
The code is something like this:
class MySerializer(Serializer):
# Some serializer fields here..
@transaction.atomic
def save(self):
foo = Foo.objects.all().select_for_update()
try:
SomeExternalSDK.doStuff(foo)
except SomeExternalSDK.SomeException as e:
log = Log(message="Uh oh")
log.save()
raise ValidationError("Something went wrong")
The problem I am facing is that when the external SDK triggers an error and I'm trying to write something to the database, that this never ends up in the database, the transaction is just rolled back.
How can I make sure that I can still write something to the database when using atomic transactions, in the except block?
Comments
Post a Comment