Generalized insertion in sqlalchemy using a dictionary
I am creating an application in Flask and I have several SQLAlchemy models. I have a dictionary with key / value pairs for each model type.
I want generic insertion using a dictionary ... would that require mapping? I know wtforms.ext.sqlalchemy.orm.model_form () generates an object with populate_obj (model) so this is possible. I have combed through the documentation but cannot find it. I can commit later, but this now requires a shortcut to populate the object. Please, does anyone have any experience?
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))
source to share
An idiomatic way to unpack a dictionary is to use the double star operator **
.
To use it with 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 must match the attribute names of the class. Unpacking in this way is the same as:
employee = Employee(firstname='John', lastname='Smith')
You can also do this with a list if you define __init__
(or another method) with positional arguments, but you only use one star:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
employee_data = ['John', 'Smith']
employee = Employee(*employee_data)
...
Note that the order of the values ββis important.
source to share