Django数据库没有更新

时间:2014-06-17 14:55:37

标签: python django sqlite

我有以下功能:

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

当我调用此函数时,game.matched_withother_game,应该是;但是,other_game.matched_with会停留None。因此,数据库未使用other_game的新matched_with信息进行更新。为什么?数据库是sqlite3。

1 个答案:

答案 0 :(得分:1)

尝试保存game,然后再将其附加到other_game

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

然后,这将使用新创建的other_game实例保存game

详细了解文档中的save()

相关问题