【问题标题】:SQLAlchemy mapping many-to-many join table to list of keysSQLAlchemy 将多对多连接表映射到键列表
【发布时间】:2022-08-24 12:45:55
【问题描述】:

我有两个具有多对多关系的表:

purchase_order = Table(
    \"purchase_order\",
    metadata,
    Column(\"name\", String, nullable=False, primary_key=True),
    ...
)

shipment = Table(
    \"shipment\",
    metadata,
    Column(\"identifier\", String, nullable=False, primary_key=True),
)

shipment_po = Table(
    \"shipment_po\",
    metadata,
    Column(
        \"shipment_identifier\",
        String,
        ForeignKey(\"shipment.identifier\"),
        nullable=False,
        primary_key=True,
    ),
    Column(
        \"purchase_order_name\",
        String,
        ForeignKey(\"purchase_order.name\"),
        nullable=False,
        primary_key=True,
    ),
)

我想将它们映射到这样的类:

class Shipment:
    def __init__(
        self,
        identifier: str,
        purchase_order_names: list[str],
    ):
    ...

(请注意, purchase_order_names 只是 str 的列表,而不是某些 PurchaseOrder 对象的列表。)

这样我就可以像这样创建它们(我有责任确保此处存在 purchase_order 行):

session.add(Shipment(\"my_shipment\", purchase_order_names=[\"my_po_1\", \"my_po_2\"]))

像这样获取:

session.query(Shipment).filter_by(identifier=\"my_shipment\").one()

并像这样更新:

shipment.purchase_order_names.append(\"my_po_3\")

这支持吗?

    标签: python sqlalchemy


    【解决方案1】:

    您可以通过将 validator 添加到创建 PurchaseOrder from the provided name 的 Shipment 来执行此操作:

    from sqlalchemy import orm
    
    class Shipment:
        ...
        @orm.validates('purchase_orders')
        def validate_purchase_orders(self, key, purchase_order):
            return PurchaseOrder(name=purchase_order)
    

    如果您需要更多控制权,您可以创建一个custom collection class

    【讨论】:

      猜你喜欢
      • 2014-04-02
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-04
      • 1970-01-01
      相关资源
      最近更新 更多