Python 在SqlAlchemy中将子类添加到会话时违反外键
我对目前的情况有所了解:Python 在SqlAlchemy中将子类添加到会话时违反外键,python,postgresql,sqlalchemy,Python,Postgresql,Sqlalchemy,我对目前的情况有所了解: Base = declarative_base() class Parent(Base): __tablename__ = 'parent' id = Column(String(32), primary_key=True, index=True) class Child(Parent): __tablename__ = 'child' parent_id = Column(ForeignKey('parent.id'), pr
Base = declarative_base()
class Parent(Base):
__tablename__ = 'parent'
id = Column(String(32), primary_key=True, index=True)
class Child(Parent):
__tablename__ = 'child'
parent_id = Column(ForeignKey('parent.id'), primary_key=True)
other_field = Column(String(32))
class Other(Base):
__tablename__ = 'other'
id = Column(String(32), primary_key=True, index=True)
reference_to_parent = Column(ForeignKey('parent.id'), primary_key=True)
child = Child(id='some_id', other_field="blah")
session.add(child)
other = Other(id="some_other_id", reference_to_parent='some_id')
session.add(other)
session.commit() # <-- sqlalchemy.exc.IntegrityError
但是,如果我这样做:
child = Child(id='id', other_field="blah")
session.add(child)
session.commit() . # <-- note the extra commit
other = Other(reference_to_parent='id')
session.add(other)
session.commit()
child=child(id='id',other_field=“blah”)
会话.添加(子级)
session.commit()。# 我认为您需要在第一次添加后添加一个会话.flush()
。Flush基本上会在挂起状态下将您的更改传递给数据库。Commit实际上会将它们写入数据库
child = Child(id='some_id', other_field="blah")
session.add(child)
session.flush()
other = Other(id="some_other_id", reference_to_parent='some_id')
session.add(other)
session.commit()
child = Child(id='some_id', other_field="blah")
session.add(child)
session.flush()
other = Other(id="some_other_id", reference_to_parent='some_id')
session.add(other)
session.commit()