【发布时间】:2018-07-20 08:26:43
【问题描述】:
我有现在的情况:
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
提交时,我收到错误:
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) insert or update on table "other" violates foreign key constraint
DETAIL: Key (reference_to_parent)=(some_id) is not present in table "parent".
但是,如果我这样做:
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()
我没有收到这样的错误。似乎 SQLAlchemy 无法识别我添加到会话中的孩子实际上是 Parent 的一个实例,并将在该表中创建一行。
知道我做错了什么吗?感觉不需要提交。
【问题讨论】:
标签: python postgresql sqlalchemy