Shouldn’t it make sense to make it:

User.objects.first() ?

I assume first() is just a custom method on the objects manager, which would 
mean you could chain them, and so have objects.all().first(); this also makes 
the code more readable in a  template:
{{ users.first }} as opposed to {{ users.all.0 }}
I am +1, and if we are doing this might as well add last(); I don’t see any 
harm of adding this to the API, but I agree with Alex that I expect it to raise 
Model.DoesNotExist for consistency.
From: Maxime Haineault 
Sent: Tuesday, July 03, 2012 12:27 AM
To: [email protected] 
Subject: I think adding a "first" method to the QuerySet be useful.

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 NoneB) 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 NoneD) Try/except:

    qs = User.objects.all()    try:     return qs[0]    except IndexError:     
return NoneThose examples have been taken from this post on StackOverflow 
(which also contains the 
answer):http://stackoverflow.com/questions/5123839/fastest-way-to-get-the-first-object-from-a-queryset-in-django--
 
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-developers/-/JleI1VvzPXIJ.
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.

Daniel Sokolowski
Web Engineer
Danols Web Engineering
http://webdesign.danols.com/

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