Django - Expression based model constraints

Posted by rtmie on Stack Overflow See other posts from Stack Overflow or by rtmie
Published on 2010-06-01T10:03:31Z Indexed on 2010/06/01 11:13 UTC
Read the original article Hit count: 174

Filed under:
|

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')

© Stack Overflow or respective owner

Related posts about python

Related posts about django