Skip to content Skip to sidebar Skip to footer

Sqlalchemy : Association Table For Many-to-many Relationship Between Template_id And Department. How Can I Delete A Relationship?

Department = models.department.Department association_table = Table('template_department', models.base.Base.instance().get_base().metadata, Column('template_

Solution 1:

In MySQL you can use row constructors and the IN-operator to remove rows from association_table that match the pairs. For example if you had list of template_id, department_id pairs such as:

to_remove = [(1, 1), (2, 2), (3, 3), ...]

then you could

from sqlalchemy import tuple_

stmt = association_table.delete().\
    where(tuple_(association_table.c.template_id,
                 association_table.c.department_id).in_(to_remove))

session.execute(stmt)
...

Note that this bypasses normal ORM book keeping, so instances that exist in your session may now contain stale data. If you intend to commit right away and reload data if needed, this is not a problem.

Post a Comment for "Sqlalchemy : Association Table For Many-to-many Relationship Between Template_id And Department. How Can I Delete A Relationship?"