I am using SQLAlchemy maximum column length recipe from my previous question (SQLAlchemy - maximum column length). Since I upgraded to SQLAlchemy 0.7, the LengthValidator
cannot be installed using the following expression:
inst.impl.extensions.insert(0, LengthValidator(col.type.length))
The extension
attribute is not defined in SQLAchemy 0.7. Is there any way how to change the recipe to work with 0.7?
Below is Ants' solution rewritten with event system of 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)
You can use sqlalchemy.orm.validates decorator:
@validates('name')
def validate_name(self, key, name):
assert len(name) <= 50
return name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With