首页 > 解决方案 > SQLAlchemy - 如何将数据库值(列)映射到我的值对象类?

问题描述

你好吗?

我一直在使用classical mappingfrom开发一些软件SQLAlchemy,我想知道如何将数据库值映射到我自己的值对象类。

例如,我有一个Wallet类,它的Money属性是一个值对象。

领域

class Money(Decimal):
    # logic here

class Wallet:
    # other attributes
    balance: Money

映射器

wallet_table = Table(
    'wallet',
    metadata,
    Column('id', UUIDType, primary_key=True),
    Column('balance', Numeric, nullable=False)
)
wallet_mapper = mapper(Wallet, wallet_table)

我如何知道SQLAlchemy在数据库上查询此数据时它应该返回balanceMoney?

标签: pythonsqlalchemy

解决方案


你可以这样做TypeDecorator

from sqlalchemy.types import TypeDecorator, NUMERIC


class Money:
    value: float  # Don't know the type you want but let's say it's a float
    # some logic


class MoneyDecorator(TypeDecorator):
    impl = NUMERIC

    def process_bind_param(self, money: Money, dialect) -> float:
        if money is not None:
            return money.value

    def process_result_value(self, value: float, dialect) -> Money:
        if value is not None:
            return Money(value)


wallet_table = Table(
    'wallet',
    metadata,
    Column('id', UUIDType, primary_key=True),
    Column('balance', MoneyDecorator, nullable=False)
)

wallet_mapper = mapper(Wallet, wallet_table)

然后你可以这样插入和选择:

stmt = wallet_table.insert({'balance': Money(123.4)})
session.execute(stmt)

stmt = wallet_table.select()
result = sesion.execute(stmt)

print(result.first()['balance'].value)  # Prints: 123.4

推荐阅读