generalised insert into sqlalchemy using dictionary

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)