What if a Django request returns nothing? It gives me an error

to_friend = User.objects.filter(username=friend_q)[0:1]

If "friend_q" is NOT inside User.username ..., it will throw an error. What is the recommended tactic?

thanks

+5
source share
3 answers

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

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

However, it is better to use the get () method to search for a specific record:

>>> 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.

Now you can catch the DoNotExist exception and take the appropriate action.

try:
   to_friend = User.objects.get(username=friend_q)
except User.DoesNotExist:
   # do something, raise error, ...
+9
source
  • FWIW, Username is unique. So U can use

    to_friend = User.objects.get(username=friend_q)
    
  • If you want to raise 404 when the user does not exist, you can also

    from django.shortcuts import get_object_or_404
    to_friend = get_object_or_404(User,username=friend_q)
    
  • , try, pythonic.

    try:
       to_friend = User.objects.get(username=friend_q)
    except User.DoesNotExist:
       to_friend = None
    
  • , get_user_or_none UserManager , None return, get_object_or_404. django, , . , 4- , None .

+5

, , , Query, . [0: 1] . , , .

to_friends = User.objects.filter(username=friend_q)
if to_friends:
    to_friend = to_friends[0]
0

All Articles