问题
Department = models.department.Department
association_table = Table('template_department', models.base.Base.instance().get_base().metadata,
Column('template_id', Integer, ForeignKey('templates.id')),
Column('department_id', Integer, ForeignKey('departments.id')))
class Template(models.base.Base.instance().get_base()):
__tablename__ = 'templates'
id = Column(Integer, primary_key=True)
tid = Column(String(7), unique=True)
....
departments = relationship('Department', secondary=association_table)
I'm trying to delete the relation between many template_id and department but I can't really come up with a query that does it. Any way to do this using Sqlalchemy?
回答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.
来源:https://stackoverflow.com/questions/44258545/sqlalchemy-association-table-for-many-to-many-relationship-between-template-id