python - 如何级联删除到 SqlAlchemy 中的多个表?

标签 python orm sqlalchemy

我有一个表,其中包含多个我想要级联删除的相关表。我在级联太远时遇到了问题。一些代码将有助于解释。

class Map(Base):
    ....
    #One to many relationship between the Map and Tile.
    #Each Map is made up of many tiles
    tiles = relationship('Tile', lazy='joined', backref='map',
                          cascade="all, delete")

class Tile(Base):
    ....
    #Reference to Map class.
    map_id = Column(Integer,
                ForeignKey('maps.id'),
                nullable=False)

    #Reference to graphics for this tile
    #This is a many to one relationship, each Graphic is used by many Tiles
    graphics_id = Column(Integer,
                     ForeignKey("graphics.id"),
                     nullable=False)

    graphics = relationship("Graphic", uselist=False)

class Graphic(Base):
    ....
    #Nothing special here

问题是,当我删除 Map Graphics 时,它也会被删除,这不是我想要的。 我认为这与级联有关。

我该如何解决这个问题,以便删除 Map 类将删除 Tiles 而不是 Graphics?

最佳答案

您的代码(除非省略了一些细节)应该按预期工作:
不应删除图形。从relationship可以看出,默认的 cascade 参数是 save-update, merge,如果你要删除一个 Map<,它不应该触发 delete/.

要进行测试,请创建一个创建Map、Tile 和Graphic 的例程;然后删除 Map 并检查 Graphic 是否被删除 - 我不希望发生这种情况。如果猜想是正确的,那么你的 Graphic 对象必须被删除,因为一些其他的 relationship

我指的是 SA 版本 0.64,但我相信默认配置在早期版本中也没有什么不同。

关于python - 如何级联删除到 SqlAlchemy 中的多个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3679601/

相关文章:

node.js - SequelizeEagerLoadingError 当模型之间的关系已经被定义时

python + sqlalchemy : calling stored procedures in a loop

python - pyshark - 来自 TCP 数据包的数据

python - 修补 sshuttle 的 firewall.py -- IPFW 到 PF

java - ORM:非主键连接列上的 OneToOne 映射 - ISBN 映射的书籍和库存

mysql - ORM 使用什么?

python - 以 SQLAlchemy 有效的方式处理一对多关系

python - SQLAlchemy 中的物化键

python - 如何在 Python 中使用 Selenium 访问弹出式登录表单

python - pandas分组并填写缺失的时间间隔序列