SQLAlchemy 在 filter_by 之后动态更新行中的值

Ger*_*ard 0 python sqlalchemy

我是 python 和 SQLAlchemy 的新手。我在python 3

我创建了一个类testtbl 来操作表。一个功能是update 我通过的地方:

myfilter = {'origin_source_id':'MX01’}.

mysql表中找到这一行origin_source_id = ‘MX01'

updatevalue = {'origin_source_id':'CAL01’}

将找到的 origin_source_id 替换为 'CAL01;

电话

testtbl.update_row(myfilter,updatevalue)
Run Code Online (Sandbox Code Playgroud)

功能

def update_row(self,locaterowfilter,updatevalue):
    self.Session.query( self.TableClass ).filter_by( **locaterowfilter ).update( updatevalue )
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

target_cls = query._mapper_zero().class_ 
AttributeError: 'NoneType' object has no attribute ‘class_’
Run Code Online (Sandbox Code Playgroud)

我不知道如何处理它。

有没有更好的方法来做到这一点?

Ilj*_*ilä 5

错误是将Table对象作为查询的主要实体传递并尝试使用的结果Query.update()

In [26]: t = Table('t', metadata,
    ...:           Column('a', Integer))

In [27]: session.query(t).update({'a': 1})
...
.../python3.6/site-packages/sqlalchemy/orm/persistence.py in _do_pre_synchronize(self)
   1383     def _do_pre_synchronize(self):
   1384         query = self.query
-> 1385         target_cls = query._mapper_zero().class_
   1386 
   1387         try:

AttributeError: 'NoneType' object has no attribute 'class_'
Run Code Online (Sandbox Code Playgroud)

这意味着您self.TableClass不是映射类。如果您希望对 a 进行更新Table,请使用核心update()结构:

stmt = self.TableClass.update().\
    where(and_(*[self.TableClass.c[key] == value
                 for key, value in locaterowfilter.items()])).\
    values(updatevalue)
self.Session.execute(stmt)
Run Code Online (Sandbox Code Playgroud)