Pergunta

well go to the question. I make this query:

Puntuaciones.objects.filter(bar__id=b).get(usuario=v.usuario2)

This works perfect, but when i put this in a if statement, like this:

if(Puntuaciones.objects.filter(bar__id=b).get(usuario=v.usuario2)):

I have a problem, when the query returns a object Puntuaciones i haven't any problems, but when there isn't a result it throws me:

Exception Value: Puntuaciones matching query does not exist.

So my question is, How i can do a if statement for a query if this query can be unsuccessful.

I try with Q objects, with exists()(this just works for querysets... I dont know how make it work. Any suggestion? Thank you

Foi útil?

Solução

get() is either returning an object or throws ObjectDoesNotExist exception, catch it with the help of try/except:

try:
    Puntuaciones.objects.filter(bar__id=b).get(usuario=v.usuario2)
    # do something if object was found
except Puntuaciones.DoesNotExist:
    # do smth if nothing found

Another options is to use exists():

if Puntuaciones.objects.filter(bar__id=b, usuario=v.usuario2).exists():
   # do something if object was found

Outras dicas

I would suggest a try: except: pair. That way, when the exception is triggered, you will be in the appropriate location to perform the code. Note that you really should use the correct exception type in the setup. Note that if you want to skip processing in the except, you need to put in an explicit pass (python noop) statement. Otherwise you will get an indentation error.

try:
  if(Puntuaciones.objects.filter(bar__id=b).get(usuario=v.usuario2)):
    # put code in here
    pass # dummy statement to be replaced by actual code.
except:
  # Put exception code here.
  pass
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top