user1703361
user1703361

Reputation: 85

SQLAlchemy if/not query session already attached

I'm getting data from a website that posts scores from high school football and putting it into a Flask project. I'm using Flask-SQLAlchemy and trying to check to see if the Game exists already; if it doesn't I create a new game in the database, if it does exist I just want to update the scores (in case there has been any corrections to the scores since my last import. Here's my code:

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

It's giving me this error when I run the code:

sqlalchemy.exc.InvalidRequestError: Object '' is already attached to session '1' (this is '2')

What would be the correct way to do this?

Upvotes: 1

Views: 2233

Answers (1)

Aleksandr Dezhin
Aleksandr Dezhin

Reputation: 636

There is no need to add an object to the session, if it was obtained from a query.

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

Upvotes: 4

Related Questions