[英]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)
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. 我正在尝试删除许多template_id和department之间的关系,但是我真的无法提出一个可以做到这一点的查询。 Any way to do this using Sqlalchemy? 使用Sqlalchemy可以做到这一点吗?
In MySQL you can use row constructors and the IN-operator to remove rows from association_table that match the pairs. 在MySQL中,您可以使用行构造函数和IN运算符从association_table中删除匹配该对的行。 For example if you had list of template_id, department_id pairs such as: 例如,如果您有template_id,department_id对的列表,例如:
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. 请注意,这会绕过常规的ORM簿记,因此会话中存在的实例现在可能包含陈旧数据。 If you intend to commit right away and reload data if needed, this is not a problem. 如果您打算立即提交并在需要时重新加载数据,这不是问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.