我有一个汉字(日文字符)列表,如下所示:
kanji_n3 = ['政', '議', '民', '連'] # But then with 367 Kanji
我有2个表:TableKanji
和TableMisc
。 TableMisc
有一个名为“jlpt”的列,其中一些目前的值为2
,但如果汉字位于3
,则必须将其更新为值kanji_n3
tableclass.py
import sqlalchemy as sqla
from sqlalchemy.orm import relationship
import sqlalchemy.ext.declarative as sqld
sqla_base = sqld.declarative_base()
class TableKanji(sqla_base):
__tablename__ = 'Kanji'
id = sqla.Column(sqla.Integer, primary_key=True)
character = sqla.Column(sqla.String, nullable=False)
misc = relationship("TableMisc", back_populates='kanji')
class TableMisc(sqla_base):
__tablename__ = 'Misc'
kanji_id = sqla.Column(sqla.Integer, sqla.ForeignKey('Kanji.id'), primary_key=True)
jlpt = sqla.Column(sqla.Integer)
kanji = relationship("TableKanji", back_populates="misc")
所以我想出的查询是,kanjiorigin_index.py:
import sqlalchemy as sqla
import sqlalchemy.orm as sqlo
from tableclass import TableKanji, TableMisc
kanji_n3 = ['政', '議', '民', '連'] # But then with 367 Kanji
session.query(TableMisc)\
.filter(TableMisc.jlpt == 2).filter(TableKanji.character in kanji_n3)\
.update({TableMisc.jlpt: TableMisc.jlpt + 1}, synchronize_session='fetch')
这会成功运行,但不会更新任何内容。输出:
2016-10-18 04:05:53,908 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1
2016-10-18 04:05:53,908 INFO sqlalchemy.engine.base.Engine ()
2016-10-18 04:05:53,908 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1
2016-10-18 04:05:53,909 INFO sqlalchemy.engine.base.Engine ()
2016-10-18 04:05:53,909 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2016-10-18 04:05:53,909 INFO sqlalchemy.engine.base.Engine SELECT "Misc".kanji_id AS "Misc_kanji_id"
FROM "Misc"
WHERE 0 = 1
2016-10-18 04:05:53,909 INFO sqlalchemy.engine.base.Engine ()
2016-10-18 04:05:53,910 INFO sqlalchemy.engine.base.Engine UPDATE "Misc" SET jlpt=("Misc".jlpt + ?) WHERE 0 = 1
2016-10-18 04:05:53,910 INFO sqlalchemy.engine.base.Engine (1,)
2016-10-18 04:05:53,911 INFO sqlalchemy.engine.base.Engine COMMIT
如何更新当前值为2且TableKanji.character位于TableMisc.jlpt
的{{1}}?我的kanji_n3
声明不是这样的吗?我还尝试添加in kanji_n3
,但结果是:
.outerjoin(TableKanji)
答案 0 :(得分:1)
似乎您的意图是对已连接的表进行更新。并非所有数据库都支持此功能。
首先,您应该使用in_
方法而不是in
运算符。
您可以先选择选择,然后更新所有选定的记录,如下所示:
records = session.query(TableMisc).\
join(TableKanji).\
filter(TableMisc.jlpt == 2).\
filter(TableKanji.character.in_(kanji_n3)).\
all()
for record in records:
record.jlpt += 1
session.commit()