繁体   English   中英

Sqlalchemy:template_id和部门之间多对多关系的关联表。 如何删除关系?

[英]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_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)

我正在尝试删除许多template_id和department之间的关系,但是我真的无法提出一个可以做到这一点的查询。 使用Sqlalchemy可以做到这一点吗?

在MySQL中,您可以使用行构造函数IN运算符association_table中删除匹配该对的行。 例如,如果您有template_id,department_id对的列表,例如:

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

那你可以

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

请注意,这会绕过常规的ORM簿记,因此会话中存在的实例现在可能包含陈旧数据。 如果您打算立即提交并在需要时重新加载数据,这不是问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM