Sqlalchemy:template_id和部门之间多对多关系的关联表.如何删除关系? [英] Sqlalchemy : association table for many-to-many relationship between template_id and department. How can I delete a relationship?

查看:84
本文介绍了Sqlalchemy:template_id和部门之间多对多关系的关联表.如何删除关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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可以做到这一点吗?

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?

推荐答案

在MySQL中,您可以使用

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

那么你就可以

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簿记,因此会话中存在的实例现在可能包含过时的数据.如果您打算立即提交并在需要时重新加载数据,那么这不是问题.

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.

这篇关于Sqlalchemy:template_id和部门之间多对多关系的关联表.如何删除关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆