history_meta Versioned mapper抛出具有双向关系的异常

时间:2017-07-12 22:19:13

标签: python sqlalchemy versioning recipe

我正在使用找到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调用的映射器需要在被调用之前创建所有相关的类。

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

1 个答案:

答案 0 :(得分:0)

此问题的一个很好的解决方法是使用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")