Anindya Guha
Anindya Guha

Reputation: 150

Django database not updating

I have the following function:

def automatch(game):
"""Automatically matches a game with another game in the database
that has the same wager. If no such game is found, the game is saved and
just waits around in the database."""

    other_game_exists = Game.objects.filter(wager=game.wager,
                                        matched_with=None).exclude(id=game.id).exists()
    if other_game_exists:
        other_game = Game.objects.filter(wager=game.wager,
                                    matched_with=None).exclude(id=game.id)[0]
        other_game = Game.objects.get(wager=game.wager,
                                    matched_with=None, id=other_game.id)
        game.matched_with = other_game
        other_game.matched_with = game
        game.save()
        other_game.save()
    else:
        game.save()

When I call this function, game.matched_with is other_game, as it should be; however, other_game.matched_with stays None. So, the database is not being updated with other_game's new matched_with information. Why? The database is sqlite3.

Upvotes: 0

Views: 458

Answers (1)

Ewan
Ewan

Reputation: 15058

Try saving the game before you attach it to other_game.

game.matched_with = other_game
game.save()
other_game.matched_with = game
other_game.save()

This will then save other_game with the newly created instance of game.

Read more about save() in the docs.

Upvotes: 1

Related Questions