【问题标题】:history_meta Versioned mapper throws an exception with bi-directional relationshipshistory_meta 版本化映射器抛出具有双向关系的异常
【发布时间】:2017-12-17 12:21:59
【问题描述】:

我正在使用 here 找到的 history_meta 配方来对我的声明性对象进行版本控制。但是,当我在两个模型之间建立双向关系时,映射器无法找到/初始化另一个模型的映射器。所以像这样。

class Child(Versioned, Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey("parent.id"))
    parent = relationship("Parent", back_populates="children")


class Parent(Versioned, Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    children = relationship("Child", back_populates="parent")

会报错

sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|Child|child, expression 'Parent' failed to locate a name ("name 'Parent' is not defined"). If this is a class name, consider adding this relationship() to the <class '__main__.Child'> class after both dependent classes have been defined.

将关系移动到类定义下方可以解决问题,但这是一个不受欢迎的解决方案。看起来历史元调用的映射器需要在调用之前创建所有相关类。

有没有办法让history_meta 以这种方式处理双向关系?

【问题讨论】:

    标签: python sqlalchemy versioning recipe


    【解决方案1】:

    解决此问题的一个好方法是使用backref 而不是back_populates。于是例子就变成了:

    class Child(Versioned, Base):
        __tablename__ = 'child'
        id = Column(Integer, primary_key=True)
        parent_id = Column(Integer, ForeignKey("parent.id"))
    
    
    class Parent(Versioned, Base):
        __tablename__ = 'parent'
        id = Column(Integer, primary_key=True)
        children = relationship("Child", backref="parent")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多