Reputation: 541
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')
Upvotes: 2
Views: 1106
Reputation: 391818
This is what model-based form validation is all about.
Define a form with a clean
method that implements these additional rules.
Always use the form's save
method to create new model objects that pass the validation rules.
http://docs.djangoproject.com/en/1.2/ref/forms/validation/#ref-forms-validation
http://docs.djangoproject.com/en/1.2/topics/forms/modelforms/#the-save-method
Upvotes: 0
Reputation: 12195
No, I don't think this will fly. The model's expecting a tuple of tuples and then the modelform base that checks it seems to grab and compare values, not run expressions.
Still, you can do it in save(), as you say - or using model validation, as DR points out
Upvotes: 0
Reputation: 599460
This sounds like a job for the new model validation support in Django 1.2.
Upvotes: 2