bhylu.com

Advertisements

Django Transactions

An atomic block groups related writes into one transaction. If a later step fails, earlier database changes in that block should not remain as a partial operation.

How it works

A reservation decrements available seats and creates a booking row. Both must happen or neither should happen. The unique user/workshop rule deliberately triggers a second-call failure in this example, after the service has attempted the decrement. The transaction restores the count when insertion fails. Database rollback does not undo an email, an uploaded file or arbitrary external work, so coordinate those separately.

Run in the supplied local Django project

This lesson uses Django 5.2.18 LTS with Python 3.12. Download the source downloader and run node download-project.mjs http://127.0.0.1:8000 with Node 22 while previewing locally. It creates a new bhylu-django-lab folder and refuses to overwrite an existing one. After deployment, the default base is bhylu.com; until then use your local preview URL.

Inside that new folder, create a virtual environment, install requirements.txt and run the complete lesson file shown below. Every lesson creates a fresh in-memory SQLite database and temporary upload storage. It does not edit the interactive lab’s db.sqlite3 or Bhylu’s database. The visible listing below is the lesson’s core code; its complete downloaded file includes the shared bootstrap.

Django does not run in Bhylu’s current browser playground. No Apache, MySQL or global PHP configuration change is needed. See the setup lesson for the full project and commands.

Example

Run .venv\Scripts\python.exe lessons\transactions.py from the downloaded project root. Download the complete lesson file; keep it under lessons/. The project’s shared models, forms, views and fixture are prerequisites, not a hidden online runtime.

lessons/transactions.py — core code

from django.contrib.auth import get_user_model
from django.db import IntegrityError
from workshops.services import reserve
user = get_user_model().objects.get(username="alex")
workshop = Workshop.objects.get(slug="lamp-care")
reserve(workshop_id=workshop.pk, user=user, seats=2)
try:
    reserve(workshop_id=workshop.pk, user=user, seats=1)
except IntegrityError:
    print("Duplicate rolled back")
print(Workshop.objects.get(pk=workshop.pk).remaining)
print(Reservation.objects.count())

Expected result

Duplicate rolled back
5
1

Only the first reservation remains, with five seats still available. The failed duplicate has not consumed another seat. This is a meaningful invariant test, not merely a check that atomic is present in the source.

Use Django’s versioned official documentation for exact API contracts and the deployment checklist before a separate release.

Advertisements