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


Question

Is there any Django function which will let me get an object form the database, or None if nothing matches?

Right now I'm using something like:

foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None

But that's not very clear, and it's messy to have everywhere.

1
96
10/2/2009 10:15:33 PM

Accepted Answer

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()
85
7/30/2013 4:37:02 AM

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon