Python 避免在多对多rel SQLAlchemy中检索要删除的对象

Python 避免在多对多rel SQLAlchemy中检索要删除的对象,python,sqlalchemy,many-to-many,Python,Sqlalchemy,Many To Many,有没有办法避免在多对多关系中检索要删除的对象 assign = Table('manytomany', Base.metadata, Column('pid', String(...), ForeignKey('parent.pid')), Column('cid', String(...), ForeignKey('child.cid')) ) class Parent(): .... childs = relationship("Child", second

有没有办法避免在多对多关系中检索要删除的对象

assign = Table('manytomany', Base.metadata,
    Column('pid', String(...), ForeignKey('parent.pid')),
    Column('cid', String(...), ForeignKey('child.cid'))
)

class Parent():
    ....
    childs = relationship("Child", secondary = assign, backref = 'parent')
我知道我能做到:

obj = session.query(Table).get(pk_id)
session.delete(obj)
但我希望只有一个数据库访问权限,比如:

session.query(Table).filter_by(id = pk_id).delete()
由于多对多rel,我出现了一个错误:

'无法删除或更新父行:外键约束失败…'

可能吗? 使用session.query()会首先从数据库中检索对象的数据。为了避免这种情况,您必须直接使用与ORM对象关联的表对象

session.execute(Parent.__table__.delete().where(Parent.id==pk_id))
这将向数据库发出一条DELETE sql语句,删除父记录。(
Parent.id
Parent.\uuuu table\uuuu.c.id
的同义词)

要解决外键错误,必须先删除分配表中的记录

session.execute(assign.delete().where(assign.c.pid==pk_id))

外键错误也可以通过在
childs
关系上配置级联来解决。我自己没有这方面的经验,但是可以找到文档。只是为了补充一下这个答案。上面的where子句可以从
sqlalchemy.sql.expression
中获取
。所以你可以做
where(和uu(Parent.id==pk\u id,)
并链接到你喜欢的地方。谢谢,这是一个有用的答案。