Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind a Dictionary to a SQLAlchemy Model for Update

I have a Dictionary (from a WTForm) that has keys in it that match fields in my SQLAlchemy Model.

class Company(database.Model):
    __tablename__ = "company"
    id = database.Column(database.Integer, primary_key=True, autoincrement=True)
    name = database.Column(database.String(255), nullable=False)
    address = database.Column(database.String(255), nullable=False)
    ...

And a Dictionary:

{"name": "Apple Inc", "address": "1 Infinite Loop", ...}

Is there any easy way to set the Model's attributes to the matching Dictionary values, or do I need to follow the x = y pattern?

company.name = company_dict["name"]
company.address = company_dict["address"]...
like image 823
Kong Avatar asked Feb 10 '26 00:02

Kong


1 Answers

Assuming you actually want to create the record it should be as simple as:

company = Company.create(**company_dict)

Or for an update:

company.update(**company_dict)
like image 139
Jack Avatar answered Feb 12 '26 14:02

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!