python - SQLAlchemy - 如何将数据库值(列)映射到我的值对象类?
问题描述
你好吗?
我一直在使用classical mapping
from开发一些软件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
在数据库上查询此数据时它应该返回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
推荐阅读
- javascript - 正则表达式 - 替换最后出现的字符
- macos - 我可以使用智能文件夹的查找器项目计数作为触发器吗?
- salesforce - Salesforce REST API - 识别重复错误的来源
- angular - Ngb Typehead 结果与部分
- python - 当我尝试使用 plyfile API 访问 .ply 文件时,为什么会出现 ValueError:两个具有相同名称的属性?
- visual-studio - .NetCore 运行时标识符参数被忽略,MSBuild,Team City
- twitter - 确定状态/过滤端点的 Twitter API 速率限制
- cocoa - AVAudioBuffer 和 AVAudioFormat,将 interleaved 设置为 true 会产生零值样本数据
- spring - 我无法在嵌入式 Tomcat/Intellij 中调用我的 html 视图 - 带有 Thymeleaf 的 Springboot
- windows - PowerShell 中的 Echo 等效项