Django is it possible to have a default value for a set of queries

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

Suppose this query set is empty.

If I use employee[0], this will result in an out-of-range index error, so is it possible here to set None as the default value?

`employee[0] or None`? # This won't work, but this is what I mean.
+5
source share
4 answers

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

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

If this does not exist, you will get an exception Employee.DoesNotExistthat you need to catch. If you have more than one 99 year old employee, you will get an Employee.MultipleObjectsReturned exception, which you might want to catch.

Always django-annoying get_object_or_None if you feel lazy!

from annoying.functions import get_object_or_None

obj = get_object_or_None(Employee, age=99)

django-annoying, get_object_or_None -, :

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
+9

:

employee[0] if employee else None
+3

There is a method in Django> = 1.6 first, so you can just do:

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

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

+3
source
first_employee = employee[0] if employee.count() > 0 else None
+1
source

All Articles