[英]generalised insert into sqlalchemy using dictionary
I'm building an application in Flask and I have several SQLAlchemy models defined.我正在 Flask 中构建一个应用程序,并且我定义了几个 SQLAlchemy 模型。 I have a dictionary with key/value pairs for each of the model types.我有一个字典,其中包含每个 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.我知道 wtforms.ext.sqlalchemy.orm.model_form() 生成一个 object 和 populate_obj(model) 所以这是可能的。 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.我可以稍后执行提交,但现在需要一个快捷方式来填充 object。 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 **
. 解包字典的惯用方法是使用双星运算符**
。
To use it with flask-sqlalchemy
: 要与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')
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: 如果使用位置参数定义__init__
(或其他方法),您也可以使用列表执行此操作,但是您只使用单个星形:
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. 请注意,值的顺序是重要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.