python - SQLAlchemy 双向删除级联(没有 ORM)

标签 python mysql sqlalchemy

我有一些使用 SQLAlchemy 的 ORM 定义的模型

class HasId(object):
    @declared_attr
    def id(cls):
        return Column('id', Integer, Sequence('test_id_seq'), primary_key=True)
    ...

class TestParent(HasId, Model):
    __tablename__ = 'tests'
    discriminator = Column(String(50))
    __mapper_args__ = {'polymorphic_on': discriminator}
    ...


class FooTest(TestParent):
    __tablename__ = 'footests'
    __mapper_args__ = {'polymorphic_identity': 'footests'}
    id = Column(Integer, ForeignKey('tests.id'), primary_key=True)
    parent_id = Column(Integer, ForeignKey('footests.id', ondelete='CASCADE'))
    children = relationship('FooTest',
                            foreign_keys='FooTest.parent_id',
                            lazy='joined',
                            join_depth=2,
                            cascade='save-update, merge, delete, delete-orphan')
    ...

当我从 tests(TestParent 模型)中删除一行时不使用 ORM 时,footests 中的相应行 被删除。一切都好。

我希望能够从 ORM 外部的 footests 中删除一行,并删除 tests 中的相应行。这本质上是让级联以相反的方向工作。

这在 ORM 之外可能吗?还有另一种方式来思考这个问题吗? (数据库引擎是MySQL/Mariadb)

最佳答案

如果您使用 ORM 添加/删除,这应该可以工作:

>>> foo = FooTest()
>>> session.add(foo)
>>> session.flush()
>>> list(session.execute("SELECT * FROM tests;"))
[(u'footests', 1)]
>>> list(session.execute("SELECT * FROM footests;"))
[(1, None)]
>>> session.delete(foo)
>>> session.flush()
>>> list(session.execute("SELECT * FROM tests;"))
[]
>>> list(session.execute("SELECT * FROM footests;"))
[]

关于python - SQLAlchemy 双向删除级联(没有 ORM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35732599/

相关文章:

python - SQLAlchemy:pandas sql_query 中的聚合查询

python - 如何从 WTForms 表单自动生成完整的 HTML

python - Bash 命令仅在第一次执行

mysql - 错误 1045 : Transferring SQL database from one server to another

python - 使用子进程在 Windows 上运行 Python 脚本

mysql - 在 GROUP_CONCAT 中选择 ID

sql - 如何替换数据库表每一列中的元素?

Python SqlAlchemy + MySql 通过 JSON 列数据过滤

python - Django 枚举属性相等

python - 如果匹配,则跳过将值写入 Csv