使用SQLAlchemy删除级联外键约束错误

时间:2018-03-27 00:20:26

标签: python mysql sqlalchemy directed-graph self-reference

我稍微修改了官方example for a directed graph并添加了cascade='all, delete-orphan,如果在孩子中定义了关系,则建议用于级联删除。但是,当我尝试删除父项时,我得到一个外键约束错误。

我希望能够删除Node对象,并且还应删除所有相关边缘。使用passive_deletes = True将是首选,我也没有这样做。

我的修改完整源代码,删除了mysql连接数据:

"""a directed graph example."""

from sqlalchemy import Column, Integer, ForeignKey, \
    create_engine
from sqlalchemy.orm import relationship, sessionmaker, backref
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class Node(Base):
    __tablename__ = 'node'

    node_id = Column(Integer, primary_key=True)

    def higher_neighbors(self):
        return [x.higher_node for x in self.lower_edges]

    def lower_neighbors(self):
        return [x.lower_node for x in self.higher_edges]


class Edge(Base):
    __tablename__ = 'edge'

    lower_id = Column(
        Integer,
        ForeignKey('node.node_id'),
        primary_key=True)

    higher_id = Column(
        Integer,
        ForeignKey('node.node_id'),
        primary_key=True)

    lower_node = relationship(
        Node,
        primaryjoin=lower_id == Node.node_id,
        backref=backref('lower_edges', cascade='all, delete-orphan'))

    higher_node = relationship(
        Node,
        primaryjoin=higher_id == Node.node_id,
        backref=backref('higher_edges', cascade='all, delete-orphan'))

    def __init__(self, n1, n2):
        self.lower_node = n1
        self.higher_node = n2

engine = create_engine('mysql+pymysql:', echo=True)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)

session = sessionmaker(engine)()

# create a directed graph like this:
#       n1 -> n2 -> n1
#                -> n5
#                -> n7
#          -> n3 -> n6

n1 = Node()
n2 = Node()
n3 = Node()
n4 = Node()
n5 = Node()
n6 = Node()
n7 = Node()

Edge(n1, n2)
Edge(n1, n3)
Edge(n2, n1)
Edge(n2, n5)
Edge(n2, n7)
Edge(n3, n6)

session.add_all([n1, n2, n3, n4, n5, n6, n7])
session.commit()

session = sessionmaker(engine)()
session.query(Node).filter(Node.node_id==1).delete()
session.commit()

1 个答案:

答案 0 :(得分:0)

删除是通过session.query()。delete()完成的,它不能与SQLAlchemy级联一起使用,需要在DB中级联才能工作。