Fastest way to get the first object from a queryset in django?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Jungle Looping
--
Chapters
00:00 Fastest Way To Get The First Object From A Queryset In Django?
00:57 Answer 1 Score 48
01:03 Answer 2 Score 175
01:32 Accepted Answer Score 490
01:48 Answer 4 Score 58
02:06 Thank you
--
Full question
https://stackoverflow.com/questions/5123...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django #performance #djangomodels
#avk47
ACCEPTED ANSWER
Score 490
Django 1.6 (released Nov 2013) introduced the convenience methods first() and last() which swallow the resulting exception and return None if the queryset returns no objects.
ANSWER 2
Score 175
You can use array slicing:
Entry.objects.all()[:1].get()
Which can be used with .filter():
Entry.objects.filter()[:1].get()
You wouldn't want to first turn it into a list because that would force a full database call of all the records. Just do the above and it will only pull the first. You could even use .order_by() to ensure you get the first you want.
Be sure to add the .get() or else you will get a QuerySet back and not an object.
ANSWER 3
Score 58
Now, in Django 1.9 you have first()  method for querysets.
YourModel.objects.all().first()
This is a better way than .get() or [0] because it does not throw an exception if queryset is empty, Therafore, you don't need to check using exists()
ANSWER 4
Score 48
r = list(qs[:1])
if r:
  return r[0]
return None