0

some_json

{ 
    "id": 1,
    "foo": "foo",
    "bar": "bar",
    "baz": "baz"
}

assume all the keys in some_json are columns

then normally when i update the database, i'll do something like

item = db.query.filter_by(id=some_json['id']).first()
if item:
    item.foo = some_json['foo']
    item.bar = some_json['bar']
    item.baz = some_json['baz']
    db.session.add(item)
    db.commit()

however, this can obviously be tedious if have more and more keys is there an easier way to update the table rows just by simply passing the json?

2
  • If isinstance(some_json, dict) is True then you could try passing some_json as parameter values to an insert() statement, e.g., db.session.execute(item.__table__.insert(), some_json) Commented Jan 5, 2021 at 0:11
  • 1
    You should be able to do instance = MyModel(**json_dict); db.add(instance) if json_dict is a flat dict and its keys match column names in MyModel. Commented Jan 5, 2021 at 7:44

1 Answer 1

1

By converting json to dectionery, which maps the table model table_model in your case, you can write your code as follows:

a= {
    "id": 1,
    "foo": "foo",
    "bar": "bar",
    "baz": "baz"
    }
item = table_model.query.filter_by(id=some_json['id']).first()
if item:
    item=table_model(**a)
    db.session.add(item)
    db.commit()
Sign up to request clarification or add additional context in comments.

1 Comment

If you desired more complex handling of the data you could use something like the marshmallow-sqlalchemy library. Marshmallow would allow you quickly load orm objects from json or a dictionary. You could also define pre/post load functions on certain ORM attributes (columns) so massage the data that comes in. E.g you could define a pre load function to encrypt a password before it's saved. Super useful in building standard rest apis where the json passed between front and backend is usually just json'ed mappings of database orm objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.