SQLAlchemy循环一对一关系 [英] SQLAlchemy circular one-to-one relationship

查看:54
本文介绍了SQLAlchemy循环一对一关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试与看起来如下的SQLAlchemy建立一种循环的一对一关系(不确定正确的术语是什么):

I am trying to make a circular one-to-one relationship (not sure what the correct term is) with SQLAlchemy that looks the following:

class Parent(Base):
    __tablename__ = 'parents'
    id = db.Column(Integer, primary_key=True)
    child_id = db.Column(db.Integer,db.ForeignKey("children.id", use_alter=True))
    child = db.relationship("Child",
                        uselist=False,
                        foreign_keys=[child_id],
                        post_update=True)

class Child(Base):
    __tablename__ = 'children'
    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey("parents.id"))
    user = db.relationship("Parent",
                       uselist=False,
                       foreign_keys=[parent_id])

一切正常,直到我尝试db.drop_all()并得到sqlalchemy.sql.schema.ForeignKeyConstraint nameNone的错误.尝试建立这种圆形一对一关系时,我做错什么了吗?我真的很想能够只查询单列以获取另一列的ID,因此可以使用循环引用.

Everything works as expected until I try to db.drop_all() and I get an error that the sqlalchemy.sql.schema.ForeignKeyConstraint name is None. Am I doing something wrong when trying to make this circular one-to-one relationship? I would really like to be able to query just the single column to get the id of the other one, hence the circular reference.

推荐答案

来自 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("Parent", back_populates="child")

然后您可以全天使用Parent.child或Child.parent

Then you can Parent.child or Child.parent all day long

这篇关于SQLAlchemy循环一对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆