gpt4 book ai didi

SQLAlchemy if/not 查询 session 已附加

转载 作者:行者123 更新时间:2023-12-03 17:12:56 24 4
gpt4 key购买 nike

我从一个网站获取数据,该网站发布高中足球的分数并将其放入 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: Object '' is already attached to session '1' (this is '2')



这样做的正确方法是什么?

最佳答案

如果对象是从查询中获得的,则无需将对象添加到 session 中。

game = Games.query.filter_by(...).first()

if not game:
add_game = Games(...)
db.session.add(add_game)
else:
game.team1_score = t1_score
game.team2_score = t2_score

db.session.commit()

关于SQLAlchemy if/not 查询 session 已附加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12782846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com