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