[Fixed]-Database tranactions in django for dependent operations

1👍

Use transaction.atomic (like you have commented out) to wrap operations into single, database transaction.

from django.db import DatabaseError, transaction

if pid is None:
    try:
        with transaction.atomic():
            pobj = ProjectModel.objects.create(name="A", description="")
            sobj = StudyModel.objects.create(name="B", description="", project_id=pobj.pk)
    except DatabaseError:
        return Response(status=status.HTTP_417_EXPECTATION_FAILED)

Leave a comment