Leopd Leopd - 2 months ago 18
Python Question

Fastest way to get the first object from a queryset in django?

Often I find myself wanting to get the first object from a queryset in Django, or return

None
if there aren't any. There are lots of ways to do this which all work. But I'm wondering which is the most performant.

qs = MyModel.objects.filter(blah = blah)
if qs.count() > 0:
return qs[0]
else:
return None


Does this result in two database calls? That seems wasteful. Is this any faster?

qs = MyModel.objects.filter(blah = blah)
if len(qs) > 0:
return qs[0]
else:
return None


Another option would be:

qs = MyModel.objects.filter(blah = blah)
try:
return qs[0]
except IndexError:
return None


This generates a single database call, which is good. But requires creating an exception object a lot of the time, which is a very memory-intensive thing to do when all you really need is a trivial if-test.

How can I do this with just a single database call and without churning memory with exception objects?

Answer
r = list(qs[:1])
if r:
  return r[0]
return None