What to do when Django query returns none? It gives me error

django, python

Solution

If friend_q is not a user present in the database, to_friend will be equal to an empty list.

>>> from django.contrib.auth.models import User
>>> User.objects.filter(username='does-not-exist')
[]

However, it's better to use the get() method to lookup a specific entry:

>>> User.objects.get(username='does-exist')
<User: does-exist>
>>> User.objects.get(username='does-not-exist')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/python2.5/django/db/models/manager.py", line 120, in get
  File "/usr/lib/python2.5/django/db/models/query.py", line 305, in get
DoesNotExist: User matching query does not exist.

You can now catch the DoesNotExist exception and take appropriate actions.

try:
   to_friend = User.objects.get(username=friend_q)
except User.DoesNotExist:
   # do something, raise error, ...

Problem

``` to_friend = User.objects.filter(username=friend_q)[0:1] ``` If 'friend_q' is NOT inside the User.username...it will give error. What is the recommended tactic?

Original source