Complete worked example
python
from bootstrap_lab import django_setup
django_setup(__name__)
from bootstrap_lab import install_models
from django.db import models, transaction, IntegrityError
class Role(models.Model):
title = models.CharField(max_length=80)
country = models.CharField(max_length=2)
class Meta:
app_label = "framework_lab"
constraints = [models.CheckConstraint(condition=models.Q(country__in=["US", "IL", "UA"]), name="role_country_allowed")]
install_models(Role)
def save_country(country):
Role.objects.all().delete()
try:
with transaction.atomic():
Role.objects.create(title="Engineer", country=country)
except IntegrityError:
return {"accepted": False, "count": Role.objects.count()}
return {"accepted": True, "count": Role.objects.count()}- Reasoning
- The model has ordinary text fields plus a named constraint requiring an allowed country. The helper clears only its fictional fixture rows, attempts one insert inside atomic and converts an IntegrityError into an explicit rejected result.