Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python SQLAlchemy:一对一关系对象创建问题_Python_Sqlite_Sqlalchemy_Relationship_One To One - Fatal编程技术网

Python SQLAlchemy:一对一关系对象创建问题

Python SQLAlchemy:一对一关系对象创建问题,python,sqlite,sqlalchemy,relationship,one-to-one,Python,Sqlite,Sqlalchemy,Relationship,One To One,我是SQLAlchemy的新手,我试图运行其文档中给出的示例。然而,当我试图实例化父类时,我遇到了麻烦 基本上,我拥有的是: class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) child = relationship("Child", uselist=False, back_populates="parent") class Child(Base):

我是SQLAlchemy的新手,我试图运行其文档中给出的示例。然而,当我试图实例化父类时,我遇到了麻烦

基本上,我拥有的是:

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:relationship parent.child上的reverse_属性“parent”引用relationship child.parent,该属性不引用映射器映射器| 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错误消息想要告诉我什么


有人能帮忙吗?

好的,文档代码中有一个明显的错误。我把这篇文章发出去,以防其他人也发同样的问题

基本上,子类中的关系行必须是与父类的关系,而子类本身的关系,如文档所示

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

按预期打印出NoneNone

就这些

更新:我尝试实例化子对象而不是父对象,但得到了完全相同的错误,即sqlalchemy.exc.ArgumentError:relationship Parent.Child引用relationship Child.Parent,哪一个不引用mapper mapper | Parent | 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("Parent", back_populates="child")
                           ^^^^^^
p1 = Parent()
c1 = Child()

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