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
时,我得到了正确的答案。谢谢你容忍我!