Greetings,
Assume I have such model:
class Foo(models.Model):
type = models.ForeignKey(Type)
start_time = models.DateTimeField()
end_time models.DateTimeField()
For each Foo object that is having the same type, I need this time interval (end_time – start_time) to be unique so that creation of a second Foo with a clashing interval won’t be possible. How can this be achieved ?
See the documentation about custom validation in the admin interface.
Basically you have to create your own (model) form, lets say
CustomFooAdminFormand assign it to the admin model:and in the form you can have something like (see custom validation in forms):
Maybe you have to transform the
DateTimeFields to UNIX timestamps, before you can subtract them in SQL (UNIX_TIMESTAMP(time_end) - UNIX_TIMESTAMP (time_start)for MySQL). Or you can useDATEDIFF()in MySQL to get the difference. But note that you tie your application to a certain database if you use such special functions (as long as they are not available in other databases under the same name).