[英]How can I get/set an SqlAlchemy query value with the Column object
[英]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.