姜戈;查询集是否可以有默认值

问题描述 投票:0回答:5
employee = Employee.objects.filter('age' = 99)

我们假设这个查询集是空的。

如果我使用

employee[0]
,则会返回索引超出范围错误,那么这里是否可以将 None 作为默认值?

`employee[0] or None`? # This won't work, but this is what I mean.
django
5个回答
11
投票

如果您只想获取单个实例,请使用

get
,而不是
filter
:

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

如果不存在,您将收到一个

Employee.DoesNotExist
异常,您需要捕获该异常。如果有超过一名 99 岁的员工,您将收到 Employee.MultipleObjectsReturned 异常,您可能想要捕获该异常。

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

get_object_or_None

from annoying.functions import get_object_or_None

obj = get_object_or_None(Employee, age=99)

如果你不想使用所有烦人的 django,你可以随时在某处添加

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

8
投票

在 Django >= 1.6 上有

first
方法,所以你可以这样做:

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

但是请注意,只有当您知道 QuerySet 保证返回 1 或 0 个结果时,这才有意义。


5
投票

这应该有效:

employee[0] if employee else None

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

0
投票

我想尝试 except onDoesNotExist Exception 更具可读性:

try:
   employee = Employee.objects.get(age=99)
except Employee.DoesNotExist:
   employee = None
© www.soinside.com 2019 - 2024. All rights reserved.