简体   繁体   English

基于另一个表中的值的简单 SQLAlchemy 更新表

[英]Simple SQLAlchemy update table based on value in another table

I am a newcomer to SQLAlchemy, so please forgive what must be an elementary question.我是 SQLAlchemy 的新手,所以请原谅这个必须是基本问题的问题。

I have a database table properties (mapped in SQLALchemy as the object Property ) which contains a field MEBID .我有一个数据库表properties (在 SQLALchemy 中映射为对象Property ),其中包含一个字段MEBID I have another table mebs (mapped in SQLAlchemy as MEB ).我有另一个表mebs (在 SQLAlchemy 中映射为MEB )。 I want to set the properties.MEBID field to mebs.id where properties.PostCode == mebs.PostCode.我想将 properties.MEBID 字段设置为 mebs.id,其中 properties.PostCode == mebs.PostCode。

I can do this simply in SQL using the command我可以使用命令在 SQL 中简单地做到这一点

update properties, mebs set properties.mebid = mebs.id where mebs.PostCode = properties.PostCode

but am struggling with doing it in SQLAlchemy.但我正在努力在 SQLAlchemy 中做到这一点。 If I try the command如果我尝试命令

session.query(Property, MEB).\
  filter(Property.PostCode == MEB.PostCode).\
  update({Property.MEBID : MEB.id})

I get我得到

InvalidRequestError: This operation requires only one Table or entity be specified as the target.

I know that this must be elementary as it's such a fundamental operation, but can't work out how it's done.我知道这必须是基本的,因为它是一个如此基本的操作,但无法弄清楚它是如何完成的。

To update:更新:

for prop, meb in session.query(Property, MEB).filter(Property.PostCode == MEB.PostCode).all():
    prop.MEBID=meb.id 
    session.add(prop)

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

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