user469652
user469652

Reputation: 51261

Django; is it possible to have a default value for queryset

employee = Employee.objects.filter('age' = 99)

We assume this queryset is empty.

If I use employee[0], that will return index out of range error, so is it possible to have a None as default value here?

`employee[0] or None`? # This won't work, but this is what I mean.

Upvotes: 11

Views: 18609

Answers (5)

Hlodowig91
Hlodowig91

Reputation: 11

I guess a try except on DoesNotExist Exception is more readable :

try:
   employee = Employee.objects.get(age=99)
except Employee.DoesNotExist:
   employee = None

Upvotes: 0

Ariel
Ariel

Reputation: 3611

On Django >= 1.6 there's the first method, so you can just do:

employee = Employee.objects.filter(age=99).first()

Note, however, that this only makes sense if you know the QuerySet is guaranteed to return either 1 or 0 results.

Upvotes: 8

Dominic Rodger
Dominic Rodger

Reputation: 99771

If you just want to get a single instance, use get, not filter:

employee = Employee.objects.get(age = 99)

If that doesn't exist, you'll get a Employee.DoesNotExist exception, which you'll need to catch. If there's more than one 99 year-old employee, you'll get a Employee.MultipleObjectsReturned exception, which you may want to catch.

There's always django-annoying's get_object_or_None if you're feeling lazy!

from annoying.functions import get_object_or_None

obj = get_object_or_None(Employee, age=99)

If you don't want to use all of django-annoying, you can always add get_object_or_None somewhere, it just looks like this:

def get_object_or_None(klass, *args, **kwargs):
    """
    Uses get() to return an object or None if the object does not exist.

    klass may be a Model, Manager, or QuerySet object. All other passed
    arguments and keyword arguments are used in the get() query.

    Note: Like with get(), a MultipleObjectsReturned will be raised if
    more than one object is found.
    """
    queryset = _get_queryset(klass)
    try:
        return queryset.get(*args, **kwargs)
    except queryset.model.DoesNotExist:
        return None

Upvotes: 12

Bernhard Vallant
Bernhard Vallant

Reputation: 50796

first_employee = employee[0] if employee.count() > 0 else None

Upvotes: 1

ikostia
ikostia

Reputation: 7587

This should work:

employee[0] if employee else None

Upvotes: 5

Related Questions