SQLAlchemy中是否可以强制分配给映射列的值的最大字符串长度?我只想引发一个异常,如果分配的字符串值长于STRING类型的对应表列的长度。
谢谢
最佳答案
最简单的方法是重命名映射的列并通过属性代理它:
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
您可以轻松地排除属性的创建,甚至可以使用通用验证框架(例如formencode)。
如果您需要更多特定于SQLAlchemy的解决方案并且不介意使用特定接口(interface),则SQLAlchemy具有扩展机制来捕获属性上的事件。使用它的验证器看起来像这样:
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
# 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:
inst.impl.extensions.insert(0, LengthValidator(col.type.length))
class ValidationError(Exception):
pass
class LengthValidator(AttributeExtension):
def __init__(self, max_length):
self.max_length = max_length
def set(self, state, value, oldvalue, initiator):
if len(value) > self.max_length:
raise ValidationError("Length %d exceeds allowed %d" %
(len(value), self.max_length))
return value
然后,您可以通过在要验证的任何类上设置
__sa_instrumentation_manager__ = InstallValidatorListeners
来使用此扩展名。如果要将其应用于从其派生的所有类,也可以仅在基类上进行设置。关于python - SQLAlchemy-最大列长度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2317081/