2015-10-05 66 views
0

我有一个Django应用程序这个看似简单的测试情况下,失败:为什么我的django模型没有保存?

def test_matches(self): 
    # setup code... 

    matches = tournament.match_set.order_by('match_id') 

    matches[0].winner = 'a' 
    matches[0].save() 
    self.assertEqual(matches[0].winner, 'a') 

什么问题?

回答

4

的问题是,matches不是简单的列表,而是一个QuerySet:索引和切片一个QuerySet访问数据库,所以每个matches[0]返回一个新的比赛。因此保存未修改的对象。

由于@Wtower指出,相关的文档中发现here

这应该是书面的方式是这样的:

m = matches[0] 
    m.winner = 'a' 
    m.save() 
    self.assertEqual(matches[0].winner, 'a') 

交替时,QuerySet力评估,如果这就是你想要什么:

matches = list(tournament.match_set.order_by('match_id')) 

或更好,如果您能识别数据库中的匹配:

matches.filter(match_id=0).update(winner=0) 

这种方式是更短,不更新就地没有加载数据到python,从而消除了可能的竞争条件。但是,过滤match_id(通常)与索引到QuerySet不同。 (切片QuerySet类似matches[0:1]无法更新)

+1

https://docs.djangoproject.com/en/1.8/ref/models/querysets/#when-querysets-are-evaluated – Wtower

相关问题