[Fixed]-Custom validation in django admin breaks datetime widget

1👍

At the Database Level

The database I am using is PostgreSQL, and afaik this cannot be
enforced at the database level.

Well there are quite a few ways to do this at the database level with postgresql. Constraints are what you should look at first. While databases like mysql are limited to Unique, Foreign Key and Primary Key constraints, postgresql can actually CHECK the values that are entered into the columns.

A check constraint is the most generic constraint type. It allows you
to specify that the value in a certain column must satisfy a Boolean
(truth-value) expression.

You can create your constraint using a custom migration. But before that are you quite sure this is a situation that cannot be tackled by a together unique index on active, foo ?

The second thing that comes to mind is to create a BEFORE INSERT/UPDATE trigger to validate the data before it’s written to the database.

The advantage of using a postgesql based approach is that if someone were to modify the data using PGAdmin the constraints would still be enforced.

At the admin level.

It would probably be a lot easier for you to override the save method in the django model or the save_model method in the admin to check for constraints than your current approach.

The save_model method is given the HttpRequest, a model instance, a
ModelForm instance and a boolean value based on whether it is adding
or changing the object. Here you can do any pre- or post-save
operations.

👤e4c5

Leave a comment