没有使用'被动删除' sqlalchemy doc中的指令

时间:2015-10-30 15:04:46

标签: python sqlalchemy

我试图重现示例形式SQLAlchemy doc:
http://docs.sqlalchemy.org/en/latest/orm/collections.html#passive-deletes
并且失败了。

我的代码:

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    children = relationship("Child", cascade="all, delete-orphan", passive_deletes=True)


class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('parent.id', ondelete='CASCADE'))    

p = Parent()
p.children = [Child(), Child()]
db_session.add(p)
db_session.commit()

parent = db_session.query(Parent).first()
db_session.delete(parent)
db_session.commit()

错误:
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) update or delete on table "parent" violates foreign key constraint "child_parent_id_fkey" on table "child" DETAIL: Key (id)=(26) is still referenced from table "child". [SQL: 'DELETE FROM parent WHERE parent.id = %(id)s'] [parameters: {'id': 26}]

我做错了什么?

0 个答案:

没有答案