SQLAlchemy Columns 结果处理

SQLAlchemy Columns result processing(SQLAlchemy Columns 结果处理)
本文介绍了SQLAlchemy Columns 结果处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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

数据库中的字符串字段(例如 name)采用以下形式:

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.

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

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"

我该怎么做?

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

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

推荐答案

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

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)

现在您可以使用 StrippedString 代替 String

Now you can use StrippedString instead of String

这篇关于SQLAlchemy Columns 结果处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I make a list of all members in a discord server using discord.py?(如何使用 discord.py 列出不和谐服务器中的所有成员?)
how to change discord.py bot activity(如何更改 discord.py 机器人活动)
Issues with getting VoiceChannel.members and Guild.members to return a full list(让 VoiceChannel.members 和 Guild.members 返回完整列表的问题)
Add button components to a message (discord.py)(将按钮组件添加到消息(discord.py))
on_message() and @bot.command issue(on_message() 和@bot.command 问题)
How to edit a message in discord.py(如何在 discord.py 中编辑消息)