Given with my current data in db, I want to restrict the post method from adding another data to the database. What I want is restrict the post method in adding another data, and just update the existing data within the db.
Code:
def get(self):
predict = PredictModel.query.all()
return {'Predict': list(x.json() for x in predict)}
def post(self):
data = request.get_json()
new_predict = PredictModel(data['timelag1'],data['timelag2'],data['timelag3'],data['timelag4'],data['timelag5'])
db.session.add(new_predict)
db.session.commit()
db.session.flush()
return new_predict.json(),201
Current data in db:
"Predict": [
{
"timelag1":1,
"timelag2": 1,
"timelag3": 1,
"timelag4": 1,
"timelag5": 1
}
]
}
Data in db after a user entered another data:
"Predict": [
{
"timelag1":2,
"timelag2": 2,
"timelag3": 2,
"timelag4": 2,
"timelag5": 2
}
]
}
CodePudding user response:
I recommend reading this answer concerning how to do the database manipulation (especially the later ones): Flask-SQLalchemy update a row's information
you will need some kind of primary key or unique identifier to specify the row that you want to change - something like "id" here's some sample code which will probably work if you adapt it to your case:
instance = User.query.filter(User.id==id)
data=instance.update(dict(json_data))
db.session.commit()
or
num_rows_updated = User.query.filter_by(username='admin').update(dict(email='[email protected]')))
db.session.commit()