我从一个网站获取数据,该网站发布高中足球的分数并将其放入 Flask 项目中。我正在使用 Flask-SQLAlchemy 并尝试检查游戏是否已经存在;如果不是,我在数据库中创建一个新游戏,如果它确实存在,我只想更新分数(以防自上次导入以来对分数进行任何更正。这是我的代码:
"""
Save to Games Table
"""
game = Games.query.filter_by(game_date=g_date, team1_name=t1_name, team1_score=t1_score, team2_name=t2_name, team2_score=t2_score).first()
"""
Need to set it to update scores if game already exists
"""
if not game:
add_game = Games(year_id=None, team1_id=None, team1_name=t1_name, team1_score=t1_score, team2_id=None, team2_name=t2_name, team2_score=t2_score, game_date=g_date)
db.session.add(add_game)
else:
game.team1_score = t1_score
game.team2_score = t2_score
db.session.add(game)
db.session.commit()
当我运行代码时,它给了我这个错误:
sqlalchemy.exc.InvalidRequestError:对象“”已附加到会话“1”(这是“2”)
这样做的正确方法是什么?