[TransWarp] Constraints on model attributes
Roché Compaan
roche at upfrontsystems.co.za
Sun Jul 27 06:43:57 EDT 2003
* Phillip J. Eby <pje at telecommunity.com> [2003-07-26 21:46]:
> At 06:43 PM 7/26/03 +0200, Roché Compaan wrote:
> >How does one define constraints for model attributes? Last time you talked
> >about this was back in January.
>
> If you have a mdl_normalize() method on a feature's 'referencedType', it
> is called with any value assigned to the feature (or added, if the feature
> is a collection). You can also define cardinality via a feature's
> lowerBound and upperBound attributes.
>
> Currently, to get any validation apart from cardinality and type
> constraints, you have to define _onLink()/_onUnlink() methods, which are
> also called when changes are made to a feature.
I've played around more and _onLink and _onUnlink methods are the
perfect place for validation and constraint hooks. I don't think
anything needs to be done to model features or datatypes. Here's a
crude example:
class TextLine(model.Attribute):
referencedType = model.String
title = u''
description = u''
def constraint(self, value):
return '\n' not in value and '\r' not in value
def _validate(self, element, item):
if not isinstance(item, unicode):
raise TypeError
if self.constraint is not None and not self.constraint(item):
raise ValidationError
def _onLink(self, element, item, posn):
self._validate(element, item)
class Person(model.Element):
class Name(TextLine):
title = u'Name'
description = u'''Person's name'''
Do you see any problem with this approach?
--
Roché Compaan
Upfront Systems http://www.upfrontsystems.co.za
More information about the PEAK
mailing list