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.
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 **
.
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 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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With