作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一些使用 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/
我是一名优秀的程序员,十分优秀!