Django视图增加变量

时间:2013-09-27 06:13:32

标签: python django operators increment

当我增加一个变量时,它只会增加到2而不是3.默认值为1.我不确定我缺少什么。任何帮助表示赞赏。

def unanswered(request, template ='unanswered.html'):
    phone_number = Pool.objects.order_by('?')[0]
    pool = Pool.objects.order_by('?')[0]
    pool_list = Pool.objects.all()
    number_attempts = Pool.objects.filter(phone_number=phone_number).count()


    # unanswer number action

        if pool_list:
            if number_attempts > 3:
                return number_attempts

            else:
                x = number_attempts
                x += 1 
                print x 'returns 2'
                store = Pool(id=phone_number.id,
                             phone_number = phone_number.phone_number,
                             un_answered=x, answered=0)
                store.save()

    payload = {'pool':pool,}

    return render_to_response(template, payload, context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:1)

您的代码中没有任何for loopwhile loop,因此如果初始number_attempts为1,则会增加到2并完成流程。

我看到你想在DB中存储尝试,但你做的方式不正确。您正在将id=phone_number.id传递给Store(...),如果存在给定id,则会尝试更新现有记录。因此Pool.objects.filter(phone_number=phone_number).count()始终返回1.

您可能想将其更改为

store = Pool(phone_number = phone_number.phone_number,
             un_answered=x, answered=0)

因此,对于下一个请求,Pool.objects.filter(phone_number=phone_number).count()将为您提供2。


评论后更新:

  

我想要的只是更新1,2,3。

中的un_answered字段

在这种情况下,请不要使用.count()来获取失败尝试次数,并使用具有该计数器的对象中的字段。

所以而不是

number_attempts = Pool.objects.filter(phone_number=phone_number).count()

你可以这样做

try:
    store = Pool.objects.get(phone_number=phone_number)
    number_attempts = store.un_answered

# FIX : the original code used a bare except clause.
# Bare except clauses are EVIL. DONT use bare except clauses. NEVER.
# Or thou shall burn in the flames of hell for your eternal death....

except Pool.DoesNotExist:
    store = Pool(phone_number = phone_number.phone_number,
                 un_answered=1, answered=0)
    store.save()
    number_attempts = 1

...
if pool_list:
        if number_attempts > 3:
            return number_attempts

        else:
            x = number_attempts
            x += 1 
            print x 'returns 2'
            store.un_answered = x
            store.save()