On 3 July 2012 06:27, Maxime Haineault <[email protected]> wrote:
> One of the common pitfall I come across way to often with novices is
> something like this:
>
>     def getFirstUser():
>         return User.objects.all()[0]
>
> It looks innocuous and often wont raise any exceptions in dev because you
> develop and test with data,
> so they slip easily in production.
>
>     def getFirstUser():
>         return User.objects.all().first()
>
> If the QuerySet is empty it should just return None instead of raising an
> exception.
>
> Other methods like .last() could probably also be useful, but getting the
> first element of a QuerySet
> is the pitfall I see the most often.
>
> Surprise Poney Quizz: which is the fastest way to get the first object of a
> QuerySet ?
>
> A) Using count:
>
>     qs = User.objects.all()
>     if qs.count() > 0:
>         return qs[0]
>     else:
>         return None
>
> B) Convert to list:
>
>     r = list(qs[:1])
>     if r:
>       return r[0]
>     return None
>
>
> C) Using len:
>
>     qs = User.objects.all()
>     if len(qs) > 0:
>         return qs[0]
>     else:
>         return None
>
> D) Try/except:
>
>     qs = User.objects.all()
>     try:
>         return qs[0]
>     except IndexError:
>         return None
>

E) Use __bool__ which fetches only one batch (depends on DB):

    qs = User.objects.all()
    user = None if not qs else qs[0]

F) Use the iterator protocol

    user = next(iter(User.objects.all()), None) # you can add LIMIT or
not, see Alex's comment

-- 
Łukasz Rekucki

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en.

Reply via email to