即使在调用save()之后,Django字段也不会保持递增

时间:2015-09-28 18:54:53

标签: python django python-3.x

我到处搜索过,无法找到答案。我真的无法理解为什么这不起作用,特别是因为它适用于其他项目。无论如何,当用户得到正确的问题时,我试图将模型字段增加1。我使用Django 1.8和Python 3.5,使用factory_boy来创建测试数据。

这里是views.py函数:

def check_answer(request):
    front = request.POST.get('front')
    userAnswer = request.POST.get('ans')
    answerCards = Card.objects.filter(front=front)
    for ans in answerCards:
        if ans.back == userAnswer:
            ans.score += 1
            ans.save() # at this point calling print(ans.score) will return 1
            return HttpResponse('correct')
    answerCards.update(score=F('score') - 1) # using print statements I know it isn't hitting this line
    return HttpResponse('wrong')

这里是相关的models.py代码:

class Card(models.Model):
    front = models.CharField(max_length=512)
    back = models.CharField(max_length=512)
    deck = models.ForeignKey(Deck)
    score = models.IntegerField(default=0)

    def __repr__(self):
        return self.front + ' - ' + self.back

这里是相关的tests.py代码:

class UserFactory(factory.DjangoModelFactory):
    class Meta:
        model = User

    username = factory.Sequence(lambda n: 'user%d' % n)
    password = factory.Sequence(lambda n: 'pass%d' % n)


class DeckFactory(factory.DjangoModelFactory):
    class Meta:
        model = Deck

    author = factory.SubFactory(UserFactory)
    title = fuzzy.FuzzyText()
    description = fuzzy.FuzzyText()


class CardFactory(factory.DjangoModelFactory):
    class Meta:
        model = Card

    front = fuzzy.FuzzyText()
    back = fuzzy.FuzzyText()
    deck = factory.SubFactory(DeckFactory)
    score = random.randint(-20, 10)


class TestNotecardViews(TestCase):

    def test_add_score_to_card(self):
        # this test passes
        card = CardFactory(score=0)
        card.score += 1
        card.save()
        self.assertEqual(1, card.score)

    def test_check_answer(self):
        deck = DeckFactory.create()
        card = CardFactory.create(front='test',
                                  back='tset',
                                  deck=deck,
                                  score=0)
        # test correct answer
        data = {
                'front': card.front,
                'ans': 'tset',
        }
        resp = self.client.post(reverse('check_answer'), data=data)
        self.assertContains(resp, 'correct', 1) # this test passes
        self.assertEqual(card.score, 1) # this test fails

特别令人沮丧的是,的值发生了变化,即使在调用save()之后,它在改变它的函数返回后也不会保持这种状态。< / p>

1 个答案:

答案 0 :(得分:1)

调用视图后,需要从数据库重新加载本地版本的card。否则它们彼此无关,card无法知道数据库已更新。

resp = self.client.post(reverse('check_answer'), data=data)
card = Card.objects.get(id=card.id)
self.assertEqual(card.score, 1)