[英]Python SqlAlchemy Update Statement
Could anyone help me out with this update statement?谁能帮我解决这个更新声明? Just trying to save json value as str into a column in my database, but its not going through:只是试图将 json 值作为 str 保存到我数据库中的列中,但它没有通过:
new_bookmarks = {
fitness_discipline: {effort: str([x for x in options if x['value'] in values]).replace("'", '"')}
}
session, engine = db_connect()
athlete_bookmarks = session.query(athlete.peloton_auto_bookmark_ids).filter(
athlete.athlete_id == 1).first().peloton_auto_bookmark_ids
athlete_bookmarks_json = json.loads(athlete_bookmarks)
athlete_bookmarks_json.update(new_bookmarks)
athlete_bookmarks = json.dumps(athlete_bookmarks_json)
session.commit()
engine.dispose()
session.close()
You're re-assigning the variable athlete_bookmarks
, not setting the attribute peloton_auto_bookmark_ids
on athlete:您正在重新分配变量athlete_bookmarks
,而不是在运动员上设置属性peloton_auto_bookmark_ids
:
new_bookmarks = {
fitness_discipline: {effort: str([x for x in options if x['value'] in values]).replace("'", '"')}
}
session, engine = db_connect()
athlete = session.query(athlete).filter(athlete.athlete_id == 1).first()
athlete_bookmarks_json = json.loads(athlete_bookmarks.peloton_auto_bookmark_ids)
athlete_bookmarks_json.update(new_bookmarks)
athlete_bookmarks.peloton_auto_bookmark_ids = json.dumps(athlete_bookmarks_json)
session.commit()
Got it with the following得到它与以下
session, engine = db_connect()
athlete_bookmarks = session.query(athlete.peloton_auto_bookmark_ids).filter(
athlete.athlete_id == 1).first()
# update peloton bookmark settings per the inputs
athlete_bookmarks_json = json.loads(athlete_bookmarks.peloton_auto_bookmark_ids)
# Check if fitness discipline exists
if not athlete_bookmarks_json.get(fitness_discipline):
athlete_bookmarks_json[fitness_discipline] = {}
# Check if fitness discipline / effort exists
if not athlete_bookmarks_json.get(fitness_discipline).get(effort):
athlete_bookmarks_json[fitness_discipline][effort] = {}
athlete_bookmarks_json[fitness_discipline][effort] = json.dumps([x for x in options if x['value'] in values])
session.query(athlete.peloton_auto_bookmark_ids).filter(
athlete.athlete_id == 1).update({athlete.peloton_auto_bookmark_ids: json.dumps(athlete_bookmarks_json)})
# write back to database
session.commit()
engine.dispose()
session.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.