Hi all,

On Tue, 3 Jul 2012, Łukasz Rekucki wrote:
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.

Good point. I was doing this the other day, and couldn't come up with a nice way.

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

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

Batch could be quite large, so this could still be inefficient.

F) Use the iterator protocol

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

This is probably the most Pythonic. But none of these make the intent really clear. I love code that's readable and obvious, and first() does it for me. +1.

Cheers, Chris.
--
Aptivate | http://www.aptivate.org | Phone: +44 1223 967 838
Future Business, Cam City FC, Milton Rd, Cambridge, CB4 1UY, UK

Aptivate is a not-for-profit company registered in England and Wales
with company number 04980791.

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