Django的;是否可以为queryset设置默认值

时间:2011-01-18 10:22:47

标签: django

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

我们假设此查询集为空。

如果我使用employee[0],那将返回索引超出范围错误,那么是否可以在此处使用None作为默认值?

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

4 个答案:

答案 0 :(得分:9)

如果您只想获得一个实例,请使用get,而不是filter

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

如果不存在,您将获得Employee.DoesNotExist异常,您需要捕获该异常。如果有一个以上的99岁员工,您将获得一个您可能想要捕获的Employee.MultipleObjectsReturned异常。

如果你感到懒惰,总会有django-annoyingget_object_or_None

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

答案 1 :(得分:6)

在Django> = 1.6上有first方法,所以你可以这样做:

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

但请注意,只有在知道QuerySet保证返回1或0结果时才有意义。

答案 2 :(得分:4)

这应该有效:

employee[0] if employee else None

答案 3 :(得分:1)

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