我正在使用ibm db2驱动程序和sqlalchemy处理ibmdb2数据库。
我的模型是:
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 "
,其中值按架构用空格填充到字段的整个长度。
在query.all()输出结果之前,我需要将此行为更改为sqlalchemy类型的字符串(或其派生字符串)生成follow(例如value.strip()):
>>> "John"
我该怎么做?
@属性decorator不适用。我需要更改标准sqlalchemy字符串类的行为。
最佳答案:
我不想更改标准字符串的行为,而是创建一个新类型(然后可以将其重命名为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