繁体   English   中英

SQLAlchemy Columns结果处理

[英]SQLAlchemy Columns result processing

我正在使用ibm_db2驱动程序和sqlalchemy使用IBM DB2数据库。 我的模型是:

class User(Model):
    id          = Column('UID', Integer, primary_key=True)
    user        = Column('USER', String(20))
    password    = Column('PASSWORD', String(10))
    name        = Column('NAME', String(30))

数据库中的字符串字段(例如名称 )的形式如下:

>>> "John                                "

,其中的值通过模式填充到字段的整个长度。

我需要将此行为更改为sqlalchemy类型String(或其衍生物)生成follow(例如value.strip() ),然后通过query.all()输出结果:

>>> "John"

我怎样才能做到这一点?

@property装饰器不适用。 我需要更改标准sqlalchemy String类的行为。

我不想改变标准String的行为但是要创建一个新类型(然后你可以将它重命名为每个模块的String或者其他),但它是最干净的:

from sqlalchemy import types

class StrippedString(types.TypeDecorator):
    """
    Returns CHAR values with spaces stripped
    """

    impl = types.String

    def process_bind_param(self, value, dialect):
        "No-op"
        return value

    def process_result_value(self, value, dialect):
        """
        Strip the trailing spaces on resulting values.
        If value is false, we return it as-is; it might be none
        for nullable columns
        """
        return value.rstrip() if value else value

    def copy(self):
        "Make a copy of this type"
        return StrippedString(self.impl.length)

现在您可以使用StrippedString而不是String

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM