相同模型中的flask-sqlalchemy一对一和多对一

时间:2021-04-10 13:08:02

标签: python sqlalchemy flask-sqlalchemy

我正在尝试制作一个邀请系统,其中一个 User 有一个可以发送给多个 InvitationTokeninvitees。每个 User 只能有一个令牌(一对一),也可以是多个令牌中的受邀者(多对一)。

这是我目前所拥有的:

邀请令牌.py

class InvitationToken(db.Model, SerializeMixin, TimestampMixin):
    __tablename__ = "invitation_token"

    """
    The relationship to the User model. An InvitationToken can have many Users as invitees.
    """
    invitees = db.relationship(
        "User", back_populates="invitee_token", foreign_keys="User.invitee_token_id"
    )

    """
    The relationship to the User model. An InvitationToken can have only one User.
    """
    user_id = db.Column(UUID(as_uuid=True), db.ForeignKey("app_user.id"), index=True)
    user = db.relationship(
        "User",
        back_populates="invitation_token",
        foreign_keys=[user_id],
        uselist=False,
    )

用户.py

class User(db.Model, TimestampMixin):
    __tablename__ = "app_user"

    """
    The relationship to the InvitationToken model. A User can have only one InvitationToken.
    """
    invitation_token_id = db.Column(
        UUID(as_uuid=True), db.ForeignKey("invitation_token.id"), index=True
    )
    invitation_token = db.relationship(
        "InvitationToken",
        back_populates="user",
        cascade="delete",
        foreign_keys=[invitation_token_id],
        uselist=False,
    )

    """
    The relationship to the InvitationToken model. A User can have only one InvitationToken as invitee.
    """
    invitee_token_id = db.Column(
        UUID(as_uuid=True), db.ForeignKey("invitation_token.id"), index=True
    )
    invitee_token = db.relationship(
        "InvitationToken",
        back_populates="invitees",
        foreign_keys=[invitee_token_id],
    )

我的当前配置出现以下错误:

sqlalchemy.exc.ArgumentError: InvitationToken.user and back-reference User.invitation_token are both of the same direction symbol('MANYTOONE').  Did you mean to set remote_side on the many-to-one side ?

我错过了什么?

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,虽然我并不完全理解它。但它有效:

class InvitationToken(db.Model, SerializeMixin, TimestampMixin):
    __tablename__ = "invitation_token"

    """
    The relationship to the User model. An InvitationToken can have many Users as invitees.
    """
    invitees = db.relationship(
        "User",
        back_populates="invitee_token",
        foreign_keys="User.invitee_token_id",  # Changed this
    )

    """
    The relationship to the User model. An InvitationToken can have only one User.
    """
    user_id = db.Column(UUID(as_uuid=True), db.ForeignKey("app_user.id"), index=True)
    user = db.relationship(
        "User",
        back_populates="invitation_token",
        foreign_keys="User.invitation_token_id",  # Changed this
        uselist=False,
    )

用户保持不变。这消除了错误,并允许我运行 Flask 并让模型按照我想要的方式运行。

相关问题