【问题标题】:Flask / SQLAlchemy - one-to-one relationship syntaxFlask / SQLAlchemy - 一对一关系语法
【发布时间】:2015-05-27 05:33:31
【问题描述】:

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

当我尝试以下操作时:

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 应该可以防止这个问题。

【问题讨论】:

    标签: flask sqlalchemy flask-sqlalchemy


    【解决方案1】:

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

    首先,我发现我必须在基类和派生类中重复“id”属性。我无法将它从基类中移出,因为它被基类方法和许多其他派生类引用,同时我无法从派生类中引用基类声明,因此不得不重新声明它(有人有更好的解决方案)?我希望我没有破坏 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))
    

    【讨论】:

      【解决方案2】:

      错误提示您需要为关系设置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'
      )
      

      【讨论】:

      • 由于表是自引用的,因此该字段似乎无法用于引用:“AttributeError: 'Table' object has no attribute 'id'”
      • 您的订阅表中没有 ID?
      • 我原以为我应该使用 benefactor_id。我的基类中有一个 id: class Base(db.Model): abstract = True id = db.Column(db.Integer, primary_key=True)
      • benefactor_id 是外键。尝试在模型中添加一个 id 字段,看看它是否有效。
      • 我的模型中有一个 id;我已经更新了原始问题以澄清这一点。我很抱歉没有包含 Base 类 decl。我也尝试过引用 id - 当我声明“receiver = relationship('Subscription', uselist=False, backref='benefactor', remote_side='subscriptions.id')”时的错误是:AttributeError: 'Table' object has没有属性'id'
      猜你喜欢
      • 2016-06-15
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-14
      • 2021-07-10
      相关资源
      最近更新 更多