【问题标题】:SQLAlchemy: Issue with One-to-One relationship object creationSQLAlchemy:一对一关系对象创建的问题
【发布时间】:2016-04-06 08:52:55
【问题描述】:

我是 SQLAlchemy 的新手,我正在尝试运行其文档 Basic Relationship Patterns - One to One Relationship 中给出的示例。但是,当我尝试实例化 Parent 类时,我遇到了麻烦。

基本上,我拥有的是:

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

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

p1 = Parent()

表格是由 .tables 在 sqlite> 提示符下制作和列出的,但是在 p1 = Parent() 行我收到了这个:

sqlalchemy.exc.ArgumentError: reverse_property 'parent' on relationship Parent.child 引用关系 Child.parent,它不引用映射器 Mapper|Parent|parent

这不会发生在一对多关系中,对于这段代码,我得到了 [ ]None 打印出来,正如我所期望的那样:

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    addresses = relationship("Address", back_populates="user")

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    email = Column(String)
    user_id = Column(Integer, ForeignKey('user.id'))

    user = relationship("User", back_populates="addresses")


u1 = User()
a1 = Address()

print(u1.addresses)
print(a1.user_id)

所以,我不太明白 SQLAlchemy 错误消息试图告诉我什么。

有人可以帮忙吗?

【问题讨论】:

  • 更新: 我尝试实例化 Child 而不是 Parent,我得到了完全相同的错误,即 sqlalchemy.exc.ArgumentError: reverse_property 'parent' on relationship Parent .child 引用关系 Child.parent,不引用映射器 Mapper|Parent|parent 这是否意味着参考文档中的映射代码有缺失/多余甚至错误?

标签: python sqlite sqlalchemy relationship one-to-one


【解决方案1】:

好的,文档代码有明显错误。我发布这个以防万一其他人遇到同样的问题。

基本上Child类中的关系线,必须是到Parent类,而不是Child 类本身,如文档中所述。

此代码已更正并按预期工作(标记为修改部分):

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

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

print(p1.id)
print(c1.parent_id)

按预期打印出 NoneNone

仅此而已!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-31
    • 2013-02-08
    • 2018-11-24
    • 2011-03-23
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多