我有以下功能:
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_with
为other_game
,应该是;但是,other_game.matched_with
会停留None
。因此,数据库未使用other_game
的新matched_with
信息进行更新。为什么?数据库是sqlite3。
答案 0 :(得分:1)
尝试保存game
,然后再将其附加到other_game
。
game.matched_with = other_game
game.save()
other_game.matched_with = game
other_game.save()
然后,这将使用新创建的other_game
实例保存game
。
详细了解文档中的save()
。