[python] 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?

This question is related to python django performance django-models

The answer is


If you plan to get first element often - you can extend QuerySet in this direction:

class FirstQuerySet(models.query.QuerySet):
    def first(self):
        return self[0]


class ManagerWithFirstQuery(models.Manager):
    def get_query_set(self):
        return FirstQuerySet(self.model)

Define model like this:

class MyModel(models.Model):
    objects = ManagerWithFirstQuery()

And use it like this:

 first_object = MyModel.objects.filter(x=100).first()

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()


You should use django methods, like exists. Its there for you to use it.

if qs.exists():
    return qs[0]
return None

It can be like this

obj = model.objects.filter(id=emp_id)[0]

or

obj = model.objects.latest('id')

This could work as well:

def get_first_element(MyModel):
    my_query = MyModel.objects.all()
    return my_query[:1]

if it's empty, then returns an empty list, otherwise it returns the first element inside a list.


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.


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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to performance

Why is 2 * (i * i) faster than 2 * i * i in Java? What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism? How to check if a key exists in Json Object and get its value Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? Most efficient way to map function over numpy array The most efficient way to remove first N elements in a list? Fastest way to get the first n elements of a List into an Array Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3? pandas loc vs. iloc vs. at vs. iat? Android Recyclerview vs ListView with Viewholder

Examples related to django-models

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries "Post Image data using POSTMAN" What does on_delete do on Django models? Django values_list vs values What's the difference between select_related and prefetch_related in Django ORM? Django Model() vs Model.objects.create() 'NOT NULL constraint failed' after adding to models.py django - get() returned more than one topic How to convert Django Model object to dict with its fields and values? How do I make an auto increment integer field in Django?