我正在使用上一个问题(SQLAlchemy - 最大列长度)中的SQLAlchemy最大列长度配方.自从我升级到SQLAlchemy 0.7后,无法使用以下表达式安装LengthValidator:
inst.impl.extensions.insert(0,LengthValidator(col.type.length))
该LengthValidator属性未在SQLAchemy 0.7中定义.有没有办法如何改变配方使用0.7?
感谢,honzas
下面是用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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1042 次 |
| 最近记录: |