我使用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')
...
当我在不使用ORM 时从tests
(TestParent
模型)删除行时,footests
中的相应行会被删除。一切都好。
我希望能够从ORM 之外的footests
中删除一行,并删除tests
中的相应行。这实际上是让级联在相反的方向上工作。
这可能在ORM之外吗?还有另一种思考方式吗? (数据库引擎为MySQL / Mariadb
)
答案 0 :(得分:1)
如果您使用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;"))
[]