shaare.it

DatabaseError: deadlock detected

7 Dec 2025

1 min read

DatabaseError: deadlock detected

$ python manage.py shell
... (during concurrent transactions)
DatabaseError: deadlock detected

Why this happens

Two transactions lock resources in conflicting order.

Fix

Shorten transactions, use select_for_update(), and retry on deadlock.

Wrong code

with transaction.atomic():
    a = A.objects.get(pk=1)
    b = B.objects.get(pk=1)
    a.save(); b.save()

Fixed code

with transaction.atomic():
    a = A.objects.select_for_update().get(pk=1)
    b = B.objects.select_for_update().get(pk=1)
    a.save(); b.save()
# implement retry logic