gpt4 book ai didi

python - SQLAlchemy 列结果处理

转载 作者:太空宇宙 更新时间:2023-11-03 13:46:48 26 4
gpt4 key购买 nike

我正在使用 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))

数据库中的字符串字段(例如 name)的形式为:

>>> "John                                "

,其中值按模式用空格填充到字段的全长。

我需要将此行为更改为在 query.all():

>>> "John"

我该怎么做?

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

最佳答案

我不想改变标准 String 的行为,而是创建一个新类型(然后您可以将其重命名为 String per module basis 或其他)但这样最干净:

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

关于python - SQLAlchemy 列结果处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18413748/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com