Using Django Check Constraints to Ensure Only One Field Is Set2020-03-25
A project I was working on recently stores “scores” which may have a single typed value: an integer, or a decimal, or a duration. Because they have different types, they are stored in separate columns in the database. Therefore, for a single score, only one of these columns may be filled in (not null).
You could solve this by using model inheritance. The downside of this is that using either concrete or abstract inheritance, you’d need multiple tables. This is also a lot of work for a single differing field.
Instead of this, we settled on a single model approach with multiple value columns, only one of which should be set. The model looks something like this:
IntegerChoices is one of Django 3.0’s new enumeration types.)
value_points column should be set.
And likewise, if the
value_duration column should be set.
However confident you are in our Python code satisfying this constraint, unless you make the database enforce it, a single bug could break the assumption. For example you could accidentally write a query like:
Such bad data could have all kinds of unintended consequences. If you discover such bad data has been created for some time, it might take a long time to unravel. Best to prevent it early on if you can!
To do this, you can add a
CheckConstraint to enforce that the filled-in value column matches the
It would look this:
The constraint is defined with
Q objects, which take the same arguments as
filter(), to restrict the cases.
Here we essentially list the two valid cases, and OR them together with Python’s bitwise OR operator
Q can’t use the normal
or operator for this because of limitations in Python.
makemigrations and applying this migration, you can test the constraint out.
You can create legitimate
Score instances just fine:
But if you try save bad data, you will get an
This works great.
You can also combine this with proxy models to split
Scores based on type.
I haven’t played around with this fully but it looks like a viable alternative to multi-table inheritance.
You could even add a helper to generate classes automatically.
You can make a simple “Points” implementation without any automatic generation like this:
DURATION implementation just needs a little copy-paste-replace.
This uses a custom manager to only returns instances of the right type.
And it also overrides
__init__ to force the
I’m sure there are some other overrides to add to make this a smooth experience, but you get the idea.
For the source code of the example project used in this post, including a bonus auto-generation of the check constraint, see it here on GitHub.
I hope this post helps you further your
Interested in Django or Python training? I'm taking bookings for workshops.
One summary email a week, no spam, I pinky promise.
- Using Django Check Constraints for the Sum of Percentage Fields
- Django's Field Choices Don't Constrain Your Data
- Common Issues Using Celery (And Other Task Queues)
© 2020 All rights reserved.