Django - Expression based model constraints
- by rtmie
Is it possible to set an expression based constraint on a django model object, e.g. If I want to impose a constraint where an owner can have only one widget of a given type that is not in an expired state, but can have as many others as long as they are expired. Obviously I can do this by overriding the save method, but I am wondering if it can be done by setting constraints, e.g. some derivative of the unique_together constraint
WIDGET_STATE_CHOICES = (
('NEW', 'NEW'),
('ACTIVE', 'ACTIVE'),
('EXPIRED', 'EXPIRED')
)
class MyWidget(models.Model):
owner = models.CharField(max_length=64)
widget_type = models.CharField(max_length = 10)
widget_state = models.CharField(max_length = 10, choices = WIDGET_STATE_CHOICES)
#I'd like to be able to do something like
class Meta:
unique_together = (("owner","widget_type","widget_state" != 'EXPIRED')