base on answer of @martijn-pieters,
you can not only dynamic update column with setattr
, but also can use dynamic table and column combine with getattr
and setattr
example:
# models.py
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
# update.py
import models
def dynamic_update(dynamic_table, col_id, dynamic_cols):
"""
dynamic_table: name of the table, "User" for example
col_id: id of which column you want to update
dynamic_cols: key value pairs {name: "diana"}
"""
if hasattr(models, dynamic_table):
table = getattr(models, dynamic_table)
col_info = table.query.filter_by(id=col_id).first()
for (key, value) in dynamic_cols.items():
if hasattr(table, key):
setattr(col_info, key, value)
session.commit()
BTW, you can get more info about setattr
, getattr
, hasattr
from python offical doc
https://docs.python.org/2/library/functions.html#setattr
https://docs.python.org/2/library/functions.html#getattr
https://docs.python.org/2/library/functions.html#hasattr