我的问题是:如何通过动态过滤器动态更新数据库中的值。我想对列名保持不可知。我希望用户通过过滤器来定位行和要更改的字段的表达式。这个想法是创建一个通用函数来做到这一点。我在理解如何为此使用 set 属性时遇到问题,或者还有其他方法?谢谢
进口:
from sqlalchemy.orm import (
mapper,
relationship,
sessionmaker)
from sqlalchemy import *
数据库启动和连接
initation = 'mysql+pymysql://user:password@localhost/km'
kmdb = create_engine( initation, pool_recycle=3600 ) # connect to server
kmdb.echo = False
Conn = kmdb.connect()
Meta = MetaData(bind=kmdb)
My_Session = sessionmaker()
My_Session.configure( bind=kmdb )
MySession=My_Session()
表说明:
country_hdl = Table( 'km_test_mapping', Meta,
Column( 'country_mapping_id', Integer, primary_key=True ),
Column( 'origin_client_id', String( 40 ) ),
Column( 'origin_source_id', String( 30 ) ),
Column( 'origin_cntrp_country', String( 30 ) ),
Column( 'som_cntrp_country', String( 30 ) ),
Column( 'can_use', Boolean ),
UniqueConstraint( 'origin_client_id', 'origin_source_id', 'origin_cntrp_country' )
)
# 映射表到类国家
class Country( object ):
pass
mapper( Country, country_hdl )
cntry = Country()
#要传递的动态变量(要更改的过滤器和值):
#I want to dynamically search for origin_client_id = MX01 and if found replace origin_client_id with CAL01. These values are passed as variables by user
myfilter = {'origin_source_id': 'MX01’}
updatefieldvalue={'origin_client_id':'CAL01’}
#查询函数:
query = MySession.query( country_hdl ).filter_by( **myfilter )
results = query.all()
#如果找到则替换字段:
if results:
for column,value in updatefieldvalue.items():
setattr(results[0],column,value)
错误 :
Traceback (most recent call last):
File "/Users/gerardrafie/Developments/KPIMinds/sampleapp/db.py",
line 63, in <module> .
setattr(results[0],column,value) .
AttributeError: can't set attribute .
慕仙森
相关分类