How does Django handle database-level constraints versus application-level validation? Why might you use UniqueConstraint in a Meta class instead of just unique=True on a field?
Last updated
DB constraints are enforced by the engine and authoritative even under concurrency or raw SQL. App validation (forms,
full_clean()) gives friendly errors but is bypassed by bulk ops or plain.save().UniqueConstraintinMetasupports composite uniqueness across fields (replacingunique_together), whichunique=Truecan't do.It also allows conditional uniqueness via
condition=(e.g. unique only whereis_active=True) and custom constraint names.
- https://docs.djangoproject.com/en/6.1/ref/models/constraints/
- https://docs.djangoproject.com/en/6.1/ref/models/instances/
- https://github.com/netbox-community/netbox/discussions/14718
- https://jamescooke.info/djangos-model-save-vs-full_clean.html
- https://docs.djangoproject.com/en/6.1/ref/models/options/
- https://www.youtube.com/watch?v=lRTTLqha58I
- https://sarahabd.com/til/django-constraints
- https://forum.djangoproject.com/t/fields-excluded-from-model-constraint-validation/37597