4

Is there a way to avoid retrieving an object to delete in many-to-many relationship?

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')

I know I can do this:

obj = session.query(Table).get(pk_id)
session.delete(obj)

But I would like have only one database access, something like:

session.query(Table).filter_by(id = pk_id).delete()

I got an error because of the many-to-many rel:

'Cannot delete or update a parent row: a foreign key constraint fails...'

Is it possible? Thx a lot

4

1 回答 1

2

Usingsession.query()将始终首先从数据库中检索对象的数据。为避免这种情况,您必须直接使用与您的 ORM 对象关联的表对象。

session.execute(Parent.__table__.delete().where(Parent.id==pk_id))

这将向删除父记录的数据库发出单个 DELETE sql 语句。(Parent.id是的同义词Parent.__table__.c.id

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

session.execute(assign.delete().where(assign.c.pid==pk_id))
于 2013-05-30T18:36:24.823 回答