SQLAlchemy if / not查询会话是否已附加

时间:2012-10-08 13:32:47

标签: sqlalchemy flask flask-sqlalchemy

我从一个网站上获取数据,该网站发布了高中橄榄球比赛并将其放入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')

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

1 个答案:

答案 0 :(得分:4)

如果是从查询中获取对象,则无需向会话添加对象。

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()