Django: Get an object form the DB, or 'None' if nothing matches

You can also try to use django annoying (it has another useful functions!)

install it with:

pip install django-annoying

from annoying.functions import get_object_or_None
get_object_or_None(Foo, bar=baz)

To add some sample code to sorki's answer (I'd add this as a comment, but this is my first post, and I don't have enough reputation to leave comments), I implemented a get_or_none custom manager like so:

from django.db import models

class GetOrNoneManager(models.Manager):
    """Adds get_or_none method to objects
    """
    def get_or_none(self, **kwargs):
        try:
            return self.get(**kwargs)
        except self.model.DoesNotExist:
            return None

class Person(models.Model):
    name = models.CharField(max_length=255)
    objects = GetOrNoneManager()

And now I can do this:

bob_or_none = Person.objects.get_or_none(name='Bob')

In Django 1.6 you can use the first() Queryset method. It returns the first object matched by the queryset, or None if there is no matching object.

Usage:

p = Article.objects.order_by('title', 'pub_date').first()

There are two ways to do this;

try:
    foo = Foo.objects.get(bar=baz)
except model.DoesNotExist:
    foo = None

Or you can use a wrapper:

def get_or_none(model, *args, **kwargs):
    try:
        return model.objects.get(*args, **kwargs)
    except model.DoesNotExist:
        return None

Call it like this

foo = get_or_none(Foo, baz=bar)

Tags:

Python

Django