Sqlalchemy : association table for many-to-many relationship between template_id and department. How can I delete a relationship?

為{幸葍}努か 提交于 2019-12-12 04:12:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!