I have a sqlite db, created as below:
class VPN_routers(Base):
__tablename__ = 'vpnrouters'
__table_args__ = TABLE_ARGS
sp_id = Column(String(), primary_key=True)
router_id = Column(String())
external_gw = Column(String())
subnet_attached = Column(String())
vpn_connectivity = Column(String()
and the contents of the table are as below:
sp-10.1.10.148|66c49f9b-11c4-4|172.24.4.6|cb3a722e-2ec4-4caf-a34b-93004d885f28|NO
sp-10.1.10.147|282608ba-8870-l|172.24.4.7|Not Attached|NO
sp-10.1.10.149|44cc77fe-3b2e-4|172.24.4.7|50853e0b-918f-4c5f-8188-3acbb23a829a|NO
I wanted to update the row where sp_id="sp-10.1.10.147"(identifying using the sp_id) and update the subnet_id and vpn_connectivity to new values. after updating the table could be like this.
sp-10.1.10.148|66c49f9b-11c4-4|172.24.4.6|cb3a722e-2ec4-4caf-a34b-93004d885f28|NO
sp-10.1.10.147|282608ba-8870-l|172.24.4.7|cbcbeiowj-d34f5tgygt-6g7ggrydwqrer3d|YES
sp-10.1.10.149|44cc77fe-3b2e-4|172.24.4.7|50853e0b-918f-4c5f-8188-3acbb23a829a|NO
I am trying to write this update as a function where I can have the feasibility to give anyone value as an identifier(not necessarily sp_id always) of the row, and its corresponding columns new elements as inputs to the function.
ex:
update_DB(VPN_routers, identifier={'sp_id':"sp-10.1.10.147"}, changes={'subnet_attached': "cbcbeiowj-d34f5tgygt-6g7ggrydwqrer3d", 'vpn_connectivity':"YES"})
*Note: identifier and changes are not same always, the identifier will be of fixed length 1 but changes could be of variable length.
I have tried many methods, but I could not make it, completely relying on this post for an answer.
The "identifier" is easy to handle: just use Query.filter_by()
and unpack the given dictionary as keyword arguments .
Since Query.update()
accepts a dictionary with attribute names as keys, handling the changes is as easy as passing the dictionary forward:
def update_DB(cls, identifier, changes):
session.query(cls).\
filter_by(**identifier).\
update(changes, synchronize_session=False)
As long as both dictionaries use attribute names as keys, it'll work, but your example includes "subnet_id" as key, which is not an attribute of the mapped class. Perhaps it should've been "subnet_attached".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.