[Django]-How do I save multiple django models in a single transaction?

59๐Ÿ‘

โœ…

Use an atomic transaction:

Atomicity is the defining property of database transactions. atomic allows us to create a block of code within which the atomicity on the database is guaranteed. If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.

Examples:

from django.db import transaction

with transaction.atomic():
    model1.save()
    model2.save()

and

from django.db import transaction, IntegrityError

try:
    with transaction.atomic():
        model1.save()
        model2.save()
except IntegrityError:
    handle_exception()
๐Ÿ‘คLeistungsabfall

3๐Ÿ‘

Alternative solution using a decorator:

from django.db import transaction

@transaction.atomic
def myview(request):
    # This code executes inside a transaction.
    model1.save()
    model2.save()
๐Ÿ‘คMarcel

Leave a comment