FastAPI 用户制作订阅模式

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

出现异常:

sqlalchemy.exc.ArgumentError: Relationship User.followings could not determine any unambiguous local/remote column pairs based on join condition and remote_side arguments. Consider using the remote() annotation to accurately mark those elements of the join condition that are on the remote side of the relationship.

我尝试了所有方法来指示模型中的连接。我不知道该怎么办(

我的用户模型

class User(SQLAlchemyBaseUserTable[int], Base):
    ...
    followings = relationship(
        'User',
        secondary=Subscription,
        primaryjoin=(id == Subscription.c.follower_id),  # local side сторона
        secondaryjoin=(id == Subscription.c.author_id),   # remote side 
        back_populates='followers',
        remote_side=Subscription.c.author_id,
        viewonly=True
    )

    followers = relationship(
        'User',
        secondary=Subscription,
        primaryjoin=(id == Subscription.c.author_id),     # local side
        secondaryjoin=(id == Subscription.c.follower_id),  # remote side
        back_populates='followings',
        remote_side=Subscription.c.follower_id,
        viewonly = True
    )

我的订阅表

Subscription = Table(
    'followers',
    Base.metadata,
    Column('author_id', Integer, ForeignKey('user.id'), primary_key=True),
    Column('follower_id', Integer, ForeignKey('user.id'), primary_key=True)
)

python sqlalchemy many-to-many fastapiusers
1个回答
0
投票

在我看来,这段代码的主要问题是 id 我的模型继承自 Base 模型,其中指定了 Id

class PreBase:

    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

    id: Mapped[int] = mapped_column(primary_key=True)


Base = declarative_base(cls=PreBase)

但据我了解,这种方法不适合创建我需要的模型连接 对我有帮助的文章:https://docs.sqlalchemy.org/en/20/orm/join_conditions.html#self-referential-many-to-many-relationship

最终代码:

followers = Table(
    'followers',
    Base.metadata,
    Column('author_id', Integer, ForeignKey('user.id'), primary_key=True),
    Column('follower_id', Integer, ForeignKey('user.id'), primary_key=True)
)

class User(SQLAlchemyBaseUserTable[int], Base):
    id = mapped_column(Integer, primary_key=True)
    ...
    followings: Mapped[List['User']] = relationship(
        'User',
        secondary=followers,
        primaryjoin=id == followers.c.follower_id,
        secondaryjoin=id == followers.c.author_id,
        back_populates='followers',
    )

    followers: Mapped[List['User']] = relationship(
        'User',
        secondary=followers,
        primaryjoin=id == followers.c.author_id,
        secondaryjoin=id == followers.c.follower_id,
        back_populates='followings',
    )
© www.soinside.com 2019 - 2024. All rights reserved.