【问题标题】:Foreign key violation when adding child class to session in SqlAlchemy在 SqlAlchemy 中将子类添加到会话时违反外键
【发布时间】: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


    【解决方案1】:

    我认为您需要在第一次添加后添加session.flush()。 Flush 基本上会将您的更改传达给处于挂起状态的数据库。提交实际上会将它们写入数据库。

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 2012-04-26
      相关资源
      最近更新 更多