qs = User.objects.all()B) Convert to list:
if qs.count() > 0:
return qs[0]
else:
return None
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 django-d...@googlegroups.com.
To unsubscribe from this group, send email to django-develop...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-developers?hl=en.