[Answer]-Django Views Incrementing Variables

1👍

There is no any for loop or while loop in your code, so if initial number_attempts is 1, it will incremented to 2 and complete the flow.

I see you want to store attempts in the DB, but the way you are doing is not correct. You are passing id=phone_number.id to Store(...), which will try to update existing record if exists with given id. So Pool.objects.filter(phone_number=phone_number).count() always returns 1.

You may want to change it to

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

So for the next request, Pool.objects.filter(phone_number=phone_number).count() will give you 2.


Update after the comment:

All I want is to update the un_answered field from 1,2,3.

In that case, don’t use .count() to get number of failed attempts use the field from object that has that counter.

So instead of

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

you can do this

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()
👤Rohan

Leave a comment