【问题标题】:SQLAlchemy Imperatively Mapping a Composite Entity without __composite_values__SQLAlchemy 在没有 __composite_values__ 的情况下强制映射复合实体
【发布时间】: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


    【解决方案1】:

    子类化 Money 怎么样?

    class DbMoney(Money):
      def __composite_keys__(self):
        return self.amount, self.currency
    
    mapper_registry.map_imperatively(
        Transaction,
        transaction_table,
        properties={
            "value": composite(
                DbMoney,
                transaction_table.c.value_amount,
                transaction_table.c.value_currency,
            )
        },
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-22
      • 2014-06-06
      • 2021-06-09
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多