簡體   English   中英

SQLAlchemy - 我如何 map 將數據庫值(列)轉換為我的值 object ZA2F2ED4F8DC40AB66

[英]SQLAlchemy - How can I map a database value(column) to my value object class?

你好嗎?

I've been developing some software using the classical mapping from SQLAlchemy and I want to know how can I map a database value to my own value object class.

例如,我有一個Wallet class,它的Money屬性值為 object。

領域

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在數據庫上查詢此數據時,它應該將balance作為Money返回?

你可以用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM