SqlAlchemy:如何使用AssociationProxy访问左表关联对象中的额外字段?

问题描述 投票:0回答:1

我有一个非常标准的关联表

class GroupUserAssociation(Base):
    __tablename__ = "group_user_associations"
    group_id: Mapped[int] = mapped_column(ForeignKey("groups.id"), primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), primary_key=True)

    group: Mapped["Group"] = relationship(back_populates="user_associations")
    user: Mapped["User"] = relationship(back_populates="group_associations")

    membership_state: Mapped[GroupMembershipState] # A str Enum

我的例子中的“左”表:


class Group(BaseEntity):
    __tablename__ = "groups"
    
    ...

    user_associations: Mapped[List["GroupUserAssociation"]] = relationship(
        "GroupUserAssociation",
        back_populates="group",
    )

    # I want a users proxy with the shape {"user": association.user, "membership_state": association.membership_state"}
    users: AssociationProxy = association_proxy(
         ...some magic here...
    )

如何使

users
字段成为我想要的形状?

我正在查看

proxy_factory
中的
association_proxy
参数,但它的文档不是很好,我不知道如何使用它。

sqlalchemy orm fastapi
1个回答
0
投票

考虑这个问题的方法是 AssociationProxy 可以将关联表中的某些字段/属性“转发”到您要添加关联代理的模型。我们想要的“自定义”字段并不直接出现在关联表中,因此我们只需创建它即可。

class GroupUserAssociation(Base):
    ...

    @property
    user_and_membership_info(self):
        return {"user": association.user, "membership_state": association.membership_state"}

在组模型中:

class Group(BaseEntity):
    ...

    users: AssociationProxy = association_proxy(
        "user_associations",
        "user_and_membership_info"
    )
© www.soinside.com 2019 - 2024. All rights reserved.