亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過 SQLAlchemy 動態搜索和修改表中的值

通過 SQLAlchemy 動態搜索和修改表中的值

慕婉清6462132 2021-06-04 14:45:53
我的問題是:如何通過動態過濾器動態更新數據庫中的值。我想對列名保持不可知。我希望用戶通過過濾器來定位行和要更改的字段的表達式。這個想法是創建一個通用函數來做到這一點。我在理解如何為此使用 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 serverkmdb.echo = FalseConn = 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 ):    passmapper( 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 . 
查看完整描述

1 回答

?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

通過查詢表名,您查詢的是無法更改的靜態結果集。但是,如果您查詢映射的類 ( session.query(Country),那么您將能夠更改結果對象。


查看完整回答
反對 回復 2021-06-08
  • 1 回答
  • 0 關注
  • 372 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號