Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

python - generalised insert into sqlalchemy using dictionary

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))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...