使用字典将广义插入到sqlalchemy中 [英] generalised insert into sqlalchemy using dictionary
问题描述
我正在Flask中构建一个应用程序,并且定义了几个SQLAlchemy模型.我有一本字典,其中包含每种模型类型的键/值对.
I'm building an application in Flask and I have several SQLAlchemy models defined. I have a dictionary with key/value pairs for each of the model types.
我想要一个使用字典的广义插入...这需要一个映射器吗?我知道wtforms.ext.sqlalchemy.orm.model_form()会使用populate_obj(model)生成一个对象,因此这是可能的.我已经仔细阅读了文档,但找不到它.我可以稍后执行提交,但是现在需要快捷方式来填充对象.拜托,有人有专业知识吗?
I want a generalised insert using a dictionary... would this require a mapper? I know that wtforms.ext.sqlalchemy.orm.model_form() generates an object with populate_obj(model) so it is possible. I've combed through the documentation but can't find it. I can perform the commit later, but need a shortcut to populate the object for now. Please, does anyone have expertise?
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy()
db.init_app(app)
employee_data = {'firstname':'John','lastname':'Smith'}
project_data = {'name':'project1'}
dict_generalised_insert(model=Employee,dictionary=employee_data)
dict_generalised_insert(model=Project,dictionary=project_data)
def dict_generalised_insert(model=None,dictionary={})
obj = model.model()
obj.populate_obj(dictionary) # ???
return obj
class Employee(db.Model):
id = db.Column(db.Integer, primary_key=True)
firstname = db.Column(db.String(80))
lastname = db.Column(db.String(80))
class Project(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
推荐答案
解开字典的惯用方式是使用双星运算符**
.
The idiomatic way to unpack a dictionary is to use the double star operator **
.
要与flask-sqlalchemy
一起使用:
class Employee(db.Model)
id = db.Column(...)
firstname = db.Column(...)
lastname = db.Column(...)
employee_data = {'firstname':'John','lastname':'Smith'}
employee = Employee(**employee_data)
db.session.add(employee)
db.session.commit()
请注意,字典中的键必须与类的属性名称匹配.以这种方式解包与:
Be aware that the keys in the dictionary have to match the attribute names of the class. Unpacking in this manner is the same as:
employee = Employee(firstname='John', lastname='Smith')
如果您使用位置参数定义__init__
(或其他方法),但也可以使用列表来完成此操作,但是您只能使用单个星号:
You can also do this with a list if you define an __init__
(or other method) with positional arguments however you only use a single star:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
employee_data = ['John', 'Smith']
employee = Employee(*employee_data)
...
请注意,值的顺序很重要.
Note here the order of the values is what's important.
这篇关于使用字典将广义插入到sqlalchemy中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!