Python Django数据库未更新

Python Django数据库未更新,python,django,sqlite,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

我有以下功能:

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_与
其他游戏
,应该是这样的;但是,
其他游戏。与
匹配的游戏保持
。因此,数据库没有使用
other_game
的新
匹配的
信息进行更新。为什么?数据库是sqlite3。

在将
游戏附加到
其他游戏之前,请尝试保存
游戏

game.matched_with = other_game
game.save()
other_game.matched_with = game
other_game.save()
然后将
other_game
与新创建的
game
实例一起保存

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

阅读文档中的更多信息。

事实上,这是我最初的想法,但它不起作用(完全相同的问题),所以我将它改为这个。我很确定这与
save()
有关,但我不知道是什么。嗯,奇怪的是,第一次保存应该创建一个工作实例,然后可以附加到其他对象。出于好奇,如果您尝试,它是否有效:
other\u game.matched\u with=game.objects.get(id=game.id)
?我找到了问题所在!Automatch()与您之前的建议配合得很好,之前的问题是我的单元测试。数据库确实正在更新中;当我从函数返回
other\u game
并检查其
字段匹配时,我得到
game
。在我的测试中,我用相同的赌注创建了一个
game_1
和一个
game_2
,我自动执行
game_1
,愚蠢的是,我感到沮丧,因为
game_2
字段匹配的
没有更新。当我将
game_2
更新为
automatch
中返回的
other_game
时,我得到了正确的答案。谢谢你容忍我!