Flask / SQLAlchemy - 一对一关系语法

Flask / SQLAlchemy - one-to-one relationship syntax

我有一个名为 Subscription 的 Flask / SQLAlchemy 模型,它与许多其他模型(订阅者、支付等)相关联。我现在必须配对两个订阅,其中一个订阅有时称为 'benefactor',而另一个订阅称为 'recipient'。这是一个可选的一对一自引用模型。

当我尝试以下操作时:

class Base(db.Model):
    __abstract__ = True
    id = db.Column(db.Integer, primary_key=True)

class Subscription(Base):

    __tablename__ = 'subscriptions'
    benefactor_id = db.Column(db.Integer, db.ForeignKey('subscriptions.id'))
    recipient = relationship('Subscription', uselist=False, backref='benefactor')

我收到错误:

Subscription.recipient and back-reference Subscription.benefactor are both
of the same direction symbol('ONETOMANY').  Did you mean to set remote_side
on the many-to-one side ?

这仅适用于 benefactor_id 定义,但会破坏关系声明。有什么建议么?我不明白这个错误——根据我对文档的阅读,uselist=False 应该可以防止这个问题。

错误说您需要为关系设置 remote_side 关键字。你试过这样设置吗?

class Subscription(Base):

__tablename__ = 'subscriptions'
benefactor_id = db.Column(db.Integer, db.ForeignKey('subscriptions.id'))
recipient= relationship(
    'Subscription',
    uselist=False,
    remote_side=[id],
    backref='benefactor'
)

好的,我想通了,但对解决方案不是特别满意。

首先,我发现我必须在基础和派生的 class 中重复 'id' 属性。我无法将它从基础 class 中移出,因为它被基础 class 方法和许多其他派生的 class 引用,同时我无法引用基础 class 来自派生 class 的声明,所以不得不重新声明它(有人有更好的解决方案)?我希望我没有破坏 SQLAlchemy 中的任何东西——至少我所有的测试都通过了,尽管我不太喜欢这个解决方案。

其次,为了使一对一的自引用连接起作用,我声明了如下所示的关系。

class Base(db.Model):
    __abstract__ = True
    id = db.Column(db.Integer, primary_key=True)

class Subscription(Base):
    __tablename__ = 'subscriptions'
    id = db.Column(db.Integer, primary_key=True)
    benefactor_id = db.Column(db.Integer, db.ForeignKey('subscriptions.id'))
    recipient = relationship('Subscription', uselist=False,
                              backref=db.backref('benefactor', remote_side=id))