【问题标题】:SQLAlchemy ON DELETE SET NULL while using secondary table使用辅助表时 SQLAlchemy ON DELETE SET NULL
【发布时间】:2013-03-06 22:03:50
【问题描述】:

我遇到了一个基本用例——我有两个表,Nodes 和 Networks,它们使用第三个表 IPAddr 作为辅助关联表互连:

class Node(Base, BasicValidator):
    __tablename__ = 'nodes'
    id = Column(Integer, primary_key=True)

class IPAddr(Base):
    __tablename__ = 'ip_addrs'
    id = Column(Integer, primary_key=True)
    network = Column(Integer, ForeignKey('networks.id'))
    node = Column(Integer, ForeignKey('nodes.id'))
    ip_addr = Column(String(25), nullable=False)

class Network(Base, BasicValidator):
    __tablename__ = 'networks'
    id = Column(Integer, primary_key=True)
    nodes = relationship(
        "Node",
        secondary=IPAddr.__table__,
        backref="networks")

现在,当我从数据库中删除网络对象时,我收到以下错误:

详细信息:密钥 (id)=(9) 仍从表“ip_addrs”中引用。 '从网络中删除,其中 networks.id = %(id)s' ({'id': 6}, {'id': 7}, {'id': 8}, {'id': 9}, {'id': 10})

我需要做的就是在删除网络和 IPAddr 的同时保留节点

我尝试这样做:http://docs.sqlalchemy.org/en/rel_0_7/orm/relationships.html#association-object,但它没有帮助,即使使用AssociacionProxy,因为这一次一切正常,但如果我这样做,Network.nodes 返回 [None]然后删除节点:

class Node(Base, BasicValidator):
    __tablename__ = 'nodes'
    id = Column(Integer, primary_key=True)

class IPAddr(Base):
    __tablename__ = 'ip_addrs'
    id = Column(Integer, primary_key=True)
    network = Column(Integer, ForeignKey('networks.id'))
    node = Column(Integer, ForeignKey('nodes.id'))
    nodes = relationship("Node", backref="networks_assocs")
    ip_addr = Column(String(25), nullable=False)

class Network(Base, BasicValidator):
    __tablename__ = 'networks'
    id = Column(Integer, primary_key=True)
    nd = relationship("IPAddr", backref="networks")
    nodes = association_proxy('nd', 'nodes')

有人可以帮忙吗,正确的方法是什么?

【问题讨论】:

    标签: python foreign-keys sqlalchemy relationship


    【解决方案1】:

    如果你的数据库支持,你需要使用类似 ON DELETE CASCADE 的东西。

    在这里查看更多信息:http://docs.sqlalchemy.org/en/latest/orm/session.html#unitofwork-cascades

    【讨论】:

    • 我知道 ON DELETE CASCADE,在这种情况下它不能完全工作(我收到上述错误)。第二种方式似乎更有用,但并不是所有的事情都很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    相关资源
    最近更新 更多