python - SQLAlchemy 0.7 - 最大列长度

标签 python sqlalchemy

我正在使用上一个问题 (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/

相关文章:

python - 继承 : Base class method which returns an instance of itself

python - 寻找更pythonic的逻辑解决方案

python - 将 'form display text' 与 SQLAlchemy 映射属性关联的最佳位置在哪里?

mysql - 如何将此 sql 转换为 sqlalchemy 查询? (MySQL 中的年、月、计数)

python - Pylons 1.0 和 SQLAlchemy 0.6 - 如何建模?

python - 我正在尝试使用 pandas 和 sqlalchemy 将数据加载到 redshift 中

python - 是否有用于 Python 单元测试的可视化工具?

python - 是否可以在一个方法中同时使用来自 2 个实例的变量?

python - 正则表达式捕获 html 元素及其类名

python - 如何使用 SQLAlchemy 根据 ID 将对象合并到 session 中,同时保持子类的正确鉴别器?