SQLAlchemy Columns result processing

…衆ロ難τιáo~ 提交于 2019-12-06 06:34:59

问题


I'm working with a IBM DB2 database using ibm_db2 driver and sqlalchemy. My model is:

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))

String fields from the database (e.g. name) comes in the form of:

>>> "John                                "

, where the value is filled right with blanks to the full length of the field by schema.

I need to change this behavior to the sqlalchemy type String (or a derivative thereof) produced follow (e.g. value.strip()) before output results by query.all():

>>> "John"

How can I do this?

@property decorator is not applicable. I need to change the behavior of a standard sqlalchemy String class.


回答1:


I would not want to change the behaviour of the standard String but to make a new type (you can then rename it to String per module basis or whatever) but it is cleanest that way:

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)

Now you can use StrippedString instead of String



来源:https://stackoverflow.com/questions/18413748/sqlalchemy-columns-result-processing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!