Over a million developers have joined DZone.

Adding a .first() method to Django's QuerySet

DZone's Guide to

Adding a .first() method to Django's QuerySet

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

In my last Django project, we had a set of helper functions that we used a lot. The most used was helpers.first, which takes a query set and returns the first element, or None if the query set was empty.

Instead of writing this:

    object = MyModel.objects.get(key=value)
except model.DoesNotExist:
    object = None

You can write this:

def first(query):
        return query.all()[0]
        return None

object = helpers.first(MyModel.objects.filter(key=value))

Note, that this is not identical. The get method will ensure that there is exactly one row in the database that matches the query. The helper.first() method will silently eat all but the first matching row. As long as you're aware of that, you might choose to use the second form in some cases, primarily for style reasons.

But the syntax on the helper is a little verbose, plus you're constantly including helpers.py. Here is a version that makes this available as a method on the end of your query set chain. All you have to do is have your models inherit from this AbstractModel.

class FirstQuerySet(models.query.QuerySet):

    def first(self):
            return self[0]
            return None

class ManagerWithFirstQuery(models.Manager):

    def get_query_set(self):
        return FirstQuerySet(self.model)

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

    class Meta:
        abstract = True

class MyModel(AbstractModel):

Now, you can do the following.

object = MyModel.objects.filter(key=value).first()


Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Chase Seibert, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}