如何通过python dict更新sqlalchemy orm对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23152337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update sqlalchemy orm object by a python dict
提问by chao787
the dict's key names are mapping to the sqlalchemy object attrs
dict 的键名映射到 sqlalchemy 对象 attrs
ex:
前任:
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
can update from id = 3, {name: "diana"}
or id = 15, {name: "marchel", fullname: "richie marchel"}
可以从 id = 3{name: "diana"}
或 id = 15 更新,{name: "marchel", fullname: "richie marchel"}
回答by Martijn Pieters
You can use setattr()
to update attributes on an existing SQLAlchemy object dynamically:
您可以使用setattr()
动态更新现有 SQLAlchemy 对象上的属性:
user = session.query(User).get(someid)
for key, value in yourdict.iteritems():
setattr(user, key, value)
回答by vinian
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
根据@martijn-pieters 的回答,您不仅setattr
可以使用 动态更新列,还可以使用动态表和列结合getattr
和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
顺便说一句,你可以得到更多的信息setattr
,getattr
,hasattr
从蟒蛇官方文档
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#getattr
回答by Perfect
I have another solution here. It would be handy to define model method as following.
我这里有另一个解决方案。如下定义模型方法会很方便。
class ModelName(db.Model):
"""
docstring here
"""
...
def update(self, **kwargs):
for key, value in kwargs.items():
if hasattr(self, key):
setattr(self, key, value)
I hope it would solve your problem.
我希望它能解决你的问题。
Thank you
谢谢
回答by sheba
Depending on your usecase (if you don't need to validate or infer anything from the model), you can save one DB call by using filter_by
with id
to get a specific row, and update it using a dictionary like you initially wanted.
根据您的用例(如果您不需要验证或推断模型中的任何内容),您可以通过使用filter_by
withid
获取特定行来保存一个数据库调用,并使用您最初想要的字典更新它。
user_query = session.query(User).filter_by(id=someid)
data_to_update = dict(name="marchel", fullname="richie marchel")
user_query.update(data_to_update)
You might also need to add synchronize_session=False
keyword argument to your update
call, depending on the type of your session (if you use scoped_session
):
您可能还需要synchronize_session=False
在update
调用中添加关键字参数,具体取决于会话的类型(如果您使用scoped_session
):
user_query.update(data_to_update, synchronize_session=False)