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 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 else: return None
Another option would be:
qs = MyModel.objects.filter(blah = blah) try: return qs 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?
Answered By – cod3monk3y
Answer Checked By – Senaida (BugsFixing Volunteer)