Home > front end >  Python Flask: Update multiple SQL columns using PUT method
Python Flask: Update multiple SQL columns using PUT method

Time:01-20

In Python flask, if I want to update data in the Postgres database table, the below put method works. In the below code Using 'if condition' I am checking and updating the values for three columns ie for fname, lname, address.

My question is if I want to update more columns example 30 to 40 columns, should I write multiple individuals 'if statement' or Is there any optimized way to update more columns?

class TodoId(Resource):
    def put(self,email):
        data = parser.parse_args()

    todo = Model.query.get(email)

    if 'fname' in data.keys():
        todo.fname = data.get('fname')
    if 'lname' in data.keys():
        todo.lname = data.get('lname')
    if 'address' in data.keys():
        todo.address = data.get('address')

    db.session.commit()

CodePudding user response:

You can write a generic update method:

class TodoId(Resource):
    def put(self,email):
        data = parser.parse_args()

    todo = Model.query.get(email)

    for key, value in data.items():
        if hasattr(todo, key):
            setattr(todo, key, value)

    db.session.commit()

CodePudding user response:

You can use the "update" method and pass the data object to it.

class TodoId(Resource):
    def put(self,email):
        data = parser.parse_args()

    Model.query.get(email).update(data)
    db.session.commit()
  •  Tags:  
  • Related