python - Avoid retrieving object to delete in many to many rel SQLAlchemy -
is there way avoid retrieving object 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 can this:
obj = session.query(table).get(pk_id) session.delete(obj)
but have 1 database access, like:
session.query(table).filter_by(id = pk_id).delete()
i got error because of many-to-many rel:
'cannot delete or update parent row: foreign key constraint fails...'
is possible? thx lot
using session.query()
retrieve object's data database first. avoid have use table object associated orm object directly.
session.execute(parent.__table__.delete().where(parent.id==pk_id))
this issue single delete sql statement database removing parent record. (parent.id
synonym parent.__table__.c.id
)
to resolve foreign key error have delete records in assign table first.
session.execute(assign.delete().where(assign.c.pid==pk_id))