django extract bool from a list

Viewed 24

I want to extract a boolean from a list, but I get the error:

TypeError: 'bool' object is not subscriptable

I basically return two values from a function and one of them is a bool but when I want to use it I get the error

def validar_cupon(codigo_forma):

    today = date.today()

    if Promos.objects.filter(codigo = codigo_forma, inicia__lte = today, finaliza__gte = today).exists():
        desc = Promos.objects.filter(codigo = codigo_forma, inicia__lte = today, finaliza__gte = today).values_list('descuento', flat=True)
        
        return True, desc[0]
    else:
        return False

and to extract I was using the index:

vc = validar_cupon(codigo_forma)
vc1 = vc[0]

that is why I'm getting the error.

1 Answers

Sometimes your function returns False, sometimes it returns a tuple. This is not good practice. You are likely getting an error when False is returned and you are trying to index it. Without seeing the actual error I am guessing this would fix it...

def validar_cupon(codigo_forma):
    today = date.today()
    if Promos.objects.filter(codigo = codigo_forma, inicia__lte = today, finaliza__gte = today).exists():
        desc = Promos.objects.filter(codigo = codigo_forma, inicia__lte = today, finaliza__gte = today).values_list('descuento', flat=True)
        return True, desc[0]
    else:
        return False, None

at least this way it always returns a tuple with two items in it.

These edits would also make your code more readable and efficient.

def validar_cupon(codigo_forma):
    today = date.today()
    obj = Promos.objects.filter(
        codigo = codigo_forma, inicia__lte = today, finaliza__gte = today
    ).only('descuento').first()
    if obj:
        return True, obj.descuento
    else:
        return False, None
Related