tags:

views:

175

answers:

4
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?

Thank you

A: 

The reason you're getting an error is because you're trying to evaluate the Query object when there's nothing in it. The [0:1] at the end is attempting to take the first item out of an empty list. If you split up the expression a little like below, you can check for an empty list before taking an element out of it.

to_friends = User.objects.filter(username=friend_q)
if to_friends:
    to_friend = to_friends[0]
Josh Smeaton
"to_friends[0]" will yield a single object, while the op's code '[0:1]' yields a list with a single object in it. Not quite the same thing !-)
bruno desthuilliers
to_friends will never be None - it'll still be a query object that returns no results.
John Montgomery
Oh, and also, the None object is garanteed to be a singleton, so you'd be better using the identity comparison, ie:"if to_friends is not None:"
bruno desthuilliers
+3  A: 
  1. FWIW, Username is unique. So U can use

    to_friend = User.objects.get(username=friend_q)
    
  2. If you want to raise a 404 when the user doesn't exist, you may as well,

    from django.shortcuts import get_object_or_404
    to_friend = get_object_or_404(User,username=friend_q)
    
  3. To prevent error, you may simply put it in the try except block, very pythonic.

    try:
       to_friend = User.objects.get(username=friend_q)
    except User.DoesNotExist:
       to_friend = None
    
  4. Since this is a common requirement, you should consider defining get_user_or_none on the UserManager, and other managers that would require None return, similar to get_object_or_404. This was in consideration for django core, but was not included, for what ever the reason. Still, is a handy, 4 line function, for models that need None back.

Lakshman Prasad
A: 
John Montgomery
+6  A: 

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