Reputation: 73
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:
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()
Upvotes: 0
Views: 165
Reputation: 73
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()
Upvotes: 0
Reputation: 13129
You're re-assigning the variable athlete_bookmarks
, not setting the attribute peloton_auto_bookmark_ids
on athlete:
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()
Upvotes: 1