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()
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) and value is not None:
setattr(todo, key, value)
db.session.commit()