[Fabio M Costa] get_first_object_or_none shortcut for Django

I will talk about a shortcut I developed for the Django framework and always use in my apps. This code is aimed in making a quik shortcut to obtain the first object of a queryset if it exists or None otherwise.

It’s very useful when you want to display the last news in the first page of your website, but don’t want it to break if there isn’t one to show. It’s just a use case for such a code, but there are many more.

In the past I used to write something like this:

try:
    first_user = User.objects.all()[:1][0]
except IndexError:
    first_user = None

This is four lines to do a very simple task and I wanted to evolve this to use only one line of code. So I developed a function that do this to me. It’s inspired in the django.shortcuts.get_object_or_404. Let’s take a look at the code:

def get_first_object_or_none(queryset):
    try:
        return queryset[:1][0]
    except IndexError:
        return None

I’ve put this code in a module called shortcuts inside my project and now everytime I want to use it I can write this code:

from shortcuts import get_first_object_or_none
first_user = get_first_object_or_none(User.objects.all())

I think it’s a very good result and helps a lot in my coding. It also made my code more legible and easy to understand. It increased my productivity and I am publishing to increase others productivity also. Any doubts, questions os suggestions, please leave a comment.