SqlAlchemey的TypeDecorator可以访问多个列来处理特殊情况吗?

时间:2015-02-20 03:06:49

标签: python sqlalchemy

建立我的上一个SqlAlchemy question,又一次,我有另一个:如何使用TypeDecorator引用同一个表中的其他列?我不确定阅读文档是否可行。该示例并不是最好的,但请考虑在将bool转换为字符串值时发生映射的用例(is_heads - >' head'或' tails') 。如果有时我想覆盖这种行为,比如id = 1234并且只是映射值' edge'代替?

如果TypeDecorators无法做到这一点,是否还有另一种与数据库无关的方法来实现所需的结果?

import sqlalchemy.types as types    

class CoinFlipDataType(types.TypeDecorator):
    impl = types.String

    def process_bind_param(self, value, dialect):
        if value is None:
            return None
        assert value in (True, False)

        # How to reference another column in the same table here?
        if id_column_value = special_case:
            return 'edge'

        return 'heads' if value else 'tails'

    def process_result_value(self, value, dialect):
        if value is None:
            return None
        assert value in ('heads', 'tails', 'edge'), value

        # I don't care about that other column in this case

        return value == 'heads'

    def copy(self):
        return CoinFlipDataType(self.impl.length)

def data_map():
    mapper(Foo, db_foo, properties={'is_heads': db_foo.c.side})

class Foo(object):
    def __init__(self, id, is_heads):
        self.id = id
        self.is_heads = is_heads

db_foo = Table(
    'foo', metadata,
    Column('id', Integer, primary_key=True),
    Column('side', CoinFlipDataType(5), nullable=False))

0 个答案:

没有答案