Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python django how to properly test if a queryset returned a result

Tags:

python

django

I haven't had a very thorough training in python and sometimes don't know the correct way of doing things. One of these things is testing if my resultQuery returned a result or not. I find myself doing this a lot:

    try:
        user = User.objects.get(email=email)
    except DoesNotExist:
        user = User()

I don't know about python but try catches in other languages are supposed to be for exceptions and not for normal program flow. How would you do this with an if else? I guess I want something similar to:

if request.GET.get('email','') is not None:
    email = request.GET['email'])
like image 920
Chase Roberts Avatar asked Oct 03 '22 01:10

Chase Roberts


1 Answers

Your exception example is most commonly the preferred way to do things. Wikipedia has quite a nice description about this:

Python style calls for the use of exceptions whenever an error condition might arise. Rather than testing for access to a file or resource before actually using it, it is conventional in Python to just go ahead and try to use it, catching the exception if access is rejected.

Exceptions are often used as an alternative to the if-block (...). A commonly-invoked motto is EAFP, or "It is Easier to Ask for Forgiveness than Permission."

Exceptions aren't necessarily costly in Python. Again, quoting the Wikipedia example:

if hasattr(spam, 'eggs'):
    ham = spam.eggs
else:
    handle_error()

... versus:

try:
    ham = spam.eggs
except AttributeError:
    handle_error()

These two code samples have the same effect, although there will be performance differences. When spam has the attribute eggs, the EAFP sample will run faster. When spam does not have the attribute eggs (the "exceptional" case), the EAFP sample will run slower.

Specifically for Django, I would use the exception example. It is the standard way to do things in that framework, and following standards is never a bad thing :).

like image 149
jro Avatar answered Oct 06 '22 00:10

jro