我正在使用上一个问题 (SQLAlchemy - maximum column length) 中的 SQLAlchemy 最大列长度配方。由于我升级到 SQLAlchemy 0.7,因此无法使用以下表达式安装 LengthValidator
:
inst.impl.extensions.insert(0, LengthValidator(col.type.length))
extension
属性未在 SQLAchemy 0.7 中定义。有什么方法可以更改配方以使用 0.7?
最佳答案
下面是用SQLAlchemy的事件系统重写的Ants方案:
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)
关于python - SQLAlchemy 0.7 - 最大列长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7846180/