【发布时间】:2023-02-02 00:19:05
【问题描述】:
我想使用 SQLAlchemy 来构建我的关系模式,但由于项目限制,中心模型不应该对任何第三方有任何依赖,我想避免向任何类添加 __composite_values__ 方法可以用作数据库中的组合。
作为一个具体的例子,假设我有以下实体:
@dataclass(kw_only=True)
class Transaction:
id: int
value: Money
description: str
timestamp: datetime.datetime
@dataclass(kw_only=True)
class Money:
amount: int
currency: str
当然,当我尝试使用这些类创建命令式映射时,我得到了AttributeError: 'Money' object has no attribute '__composite_values__':
transaction_table = Table(
"transaction",
mapper_registry.metadata,
Column("id", BigInteger, primary_key=True),
Column("description", String(1024)),
Column(
"timestamp",
DateTime(timezone=False),
nullable=False,
server_default=text("NOW()"),
),
Column("value_amount", Integer(), nullable=False),
Column("value_currency", String(5), nullable=False),
)
mapper_registry.map_imperatively(
Transaction,
transaction_table,
properties={
"value": composite(
Money,
transaction_table.c.value_amount,
transaction_table.c.value_currency,
)
},
)
那么,我有哪些映射这些类的选项?到目前为止,我只能想到为每个实体创建一个重复包装器的解决方案做有特定于 ORM 的附件,但这看起来很讨厌。
【问题讨论】:
标签: python sqlalchemy orm