Gustavo Lisi
Gustavo Lisi

Reputation: 141

Python/Django - Acumulative variable with two or more models

Im new in python/django and first of all sorry for this dumb question... but I have a view with something like this:

index = 0

    try:
        TableA.objects.get(usuario=request.user)
        index = index + 1
    except TableA.DoesNotExist:
        index = index + 0

    try:
        TableB.objects.get(usuario=request.user)
        index = index + 1
    except TableB.DoesNotExist:
        index = index + 0

    [...]

I wanted that index was acumlative. I understand why this is not working. But how can i do that?

Upvotes: 0

Views: 39

Answers (2)

jozo
jozo

Reputation: 4742

from django.http import HttpResponse

def my_view(request):
    index = 0

    if TableA.objects.filter(usuario=request.user).exists():
        index += 1

    if TableB.objects.filter(usuario=request.user).exists():
        index += 1

    return HttpResponse("User exists in {} tables".format(index))

Upvotes: 1

Ben
Ben

Reputation: 2547

based on your code you're probably looking for something like this:

index = 0

if TableA.objects.filter(usuario=request.user).count() == 1:
    index += 1

if TableB.objects.filter(usuario=request.user).count() == 1:
    index += 1

Upvotes: 1

Related Questions