Update row (SQLAlchemy) with data from marshmallow

前端 未结 5 1836
天命终不由人
天命终不由人 2020-12-29 05:29

I\'m using Flask, Flask-SQLAlchemy, Flask-Marshmallow + marshmallow-sqlalchemy, trying to implement REST api PUT method. I haven\'t found any tutorial using SQLA and Marshma

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-29 05:53

    Latest Update [2020]:

    You might facing the issue of mapping keys to the database models. Your request body have only updated fields so, you want to change only those without affecting others. There is an option to write multiple if conditions but that's not a good approach.

    Solution You can implement patch or put methods using sqlalchemy library only.

    For example:

    YourModelName.query.filter_by(
                    your_model_column_id = 12 #change 12: where condition to find particular row
             ).update(request_data)
    

    request_data should be dict object. For ex.

    {
      "your_model_column_name_1": "Hello",
      "your_model_column_name_2": "World",
    }
    

    In above case, only two columns will be updated that is: your_model_column_name_1 and your_model_column_name_2

    Update function maps request_data to the database models and creates update query for you. Checkout this: https://docs.sqlalchemy.org/en/13/core/dml.html#sqlalchemy.sql.expression.update

提交回复
热议问题