[英]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.