0

当我增加一个变量时,它只会增加到 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))
4

1 回答 1

1

您的代码中没有任何for loopor while loop,因此如果 initialnumber_attempts为 1,它将递增到 2 并完成流程。

我看到您想将尝试存储在数据库中,但是您的操作方式不正确。您正在传递id=phone_number.idStore(...),如果存在给定的 ,它将尝试更新现有记录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()
于 2013-09-27T06:39:35.460 回答