How to create a Django model where only one row can have a specific value
In my Home Inventory app I implemented the model for Measurement and each Item has its own Measurement.
Later I got tired of selecting measurement value for each new item in the UI as in 99% cases I selected “pcs”. I didn’t want to hardcode initial value, so I started to investigate: how to allow only one row to have a specific field value? Or, in my case, how to create a Django model where only one row can have value True?
Solution
The solution is to add unique constraint on that field. Here’s my Measurement model:
So the constraint
makes it possible for only one measurement to have is_default
value set to True.
Make it work in the admin
Although the solution works, it’s also nice to make it foolproof in the admin UI.
To achieve that, I wrote the following code:
Overriding get_readonly_fields
makes it impossible to even try to select addition measurement as default.
In case one measurement is already a default measurement, for all other measurements is_default
field is not editable.
Apply default value in the form
I wanted to display the default value in the form. In the view that renders that form, I first request that value.
However, there’s no requirement for default value to exist, so this case should be handled as well.
Then I simply pass initial
arg to the form:
and the default measurement value is displayed in measurement field for all new items. That’s it!