The easiest way is to simply rename the associated column and proxy through a property:
class Something(Base): ... _foo = Column('foo', String(123)) @property def foo(self): return self._foo @foo.setter def foo(self, value): if len(value) > _foo.type.length: raise Exception("Value too long") self._foo = value
You can easily decompose the creation of a property and even use a common validation structure such as formencode.
If you need a more specific SQLAlchemy solution and don't mind using specific interfaces, then SQLAlchemy has an extension mechanism for collecting events by attribute. A validator using this will look something like this:
from sqlalchemy.orm.interfaces import AttributeExtension, InstrumentationManager from sqlalchemy.orm import ColumnProperty class InstallValidatorListeners(InstrumentationManager): def post_configure_attribute(self, class_, key, inst): """Add validators for any attributes that can be validated.""" prop = inst.prop
Then you should use this extension by setting __sa_instrumentation_manager__ = InstallValidatorListeners to any class that you want to test. You can also just set it in the Base class if you want it to apply to all classes derived from it.
Ants aasma
source share