Ниже приведено решение Антса, переписанное с помощью системы событий SQLAlchemy:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import ColumnProperty
from sqlalchemy import event
def check_string_length(cls, key, inst):
prop = inst.prop
# Only interested in simple columns, not relations
if isinstance(prop, ColumnProperty) and len(prop.columns) == 1:
col = prop.columns[0]
# if we have string column with a length, install a length validator
if isinstance(col.type, String) and col.type.length:
max_length = col.type.length
def set_(instance, value, oldvalue, initiator):
if len(value)>max_length:
raise ValueError("Length %d exceeds allowed %d" % \
(len(value), max_length))
event.listen(inst, 'set', set_)
Base = declarative_base()
event.listen(Base, 'attribute_instrument', check_string_length)