SQLAlchemy 0.7 - 最大列长

时间:2011-10-21 07:18:52

标签: python sqlalchemy

我正在使用上一个问题(SQLAlchemy - maximum column length)中的SQLAlchemy最大列长度配方。自从我升级到SQLAlchemy 0.7后,无法使用以下表达式安装LengthValidator:

  
    

inst.impl.extensions.insert(0,LengthValidator(col.type.length))

  

SQLAchemy 0.7中未定义extension属性。有没有办法如何改变配方使用0.7?

谢谢,honzas

2 个答案:

答案 0 :(得分:9)

下面是用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)

答案 1 :(得分:1)

您可以使用sqlalchemy.orm.validates decorator

@validates('name')
def validate_name(self, key, name):
    assert len(name) <= 50
    return name