gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:00:59 25 4
gpt4 key购买 nike

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

我们假设此查询集为空。

如果我使用 employee[0],它将返回索引超出范围的错误,那么这里是否可以将None作为默认值?
`employee[0] or None`? # This won't work, but this is what I mean.

最佳答案

如果只想获取一个实例,请使用 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

关于Django;是否可以为queryset设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4722925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com