SQLAlchemy 0.7 - 最大列长度

4 投票
2 回答
1560 浏览
提问于 2025-04-17 04:44

我在使用我之前问题中提到的SQLAlchemy最大列长度的做法(SQLAlchemy - 最大列长度)。但是自从我升级到SQLAlchemy 0.7后,LengthValidator就无法用下面的方式安装了:

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

在SQLAlchemy 0.7中,extension这个属性没有定义。有没有什么办法可以修改这个做法,让它在0.7版本中也能用呢?

2 个回答

1

你可以使用 sqlalchemy.orm.validates 装饰器

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

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

撰写回答