Complete worked example
python
from bootstrap_lab import django_setup
django_setup(__name__)
from bootstrap_lab import install_models
from django.db import models, connection, transaction
from django.test.utils import CaptureQueriesContext
class Role(models.Model):
title = models.CharField(max_length=80)
country = models.CharField(max_length=2)
active = models.BooleanField(default=True)
class Meta:
app_label = "framework_lab"
install_models(Role)
def publish_after_commit(fail):
Role.objects.all().delete()
events = []
try:
with transaction.atomic():
Role.objects.create(title="Saved", country="UA", active=True)
transaction.on_commit(lambda: events.append("published"))
if fail:
raise ValueError("controlled rollback")
except ValueError:
pass
return {"rows": Role.objects.count(), "events": events}- Reasoning
- The helper creates a role inside atomic, registers the callback and optionally raises a controlled error before leaving the block. On success the row remains and the callback runs after commit.