gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:41:20 25 4
gpt4 key购买 nike

我有一些使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com