使用字典将广义插入到 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屋!