[英]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.