当我要求模型管理器获取一个对象时,当没有匹配的对象时,它会引发DoesNotExist。

go = Content.objects.get(name="baby")

而不是DoesNotExist,我怎么能去是None代替?


当前回答

这是一个讨厌的函数,你可能不想重新实现:

from annoying.functions import get_object_or_None
#...
user = get_object_or_None(Content, name="baby")

其他回答

Maybe更好用:

User.objects.filter(username=admin_username).exists()

我认为使用get_object_or_404()是个不错的主意。

from django.shortcuts import get_object_or_404

def my_view(request):
    my_object = get_object_or_404(MyModel, pk=1)

这个例子等价于:

from django.http import Http404

def my_view(request):
    try:
        my_object = MyModel.objects.get(pk=1)
    except MyModel.DoesNotExist:
        raise Http404("No MyModel matches the given query.")

你可以在django在线文档中阅读更多关于get_object_or_404()的信息。

如果发生这样的事呢?

go = (Content.objects.filter(name="value") or [None])[0]

下面是helper函数的一个变体,它允许你有选择地传入一个QuerySet实例,以防你想从模型的所有对象QuerySet之外的QuerySet中获得唯一的对象(如果存在)(例如,从属于父实例的子项的子集中):

def get_unique_or_none(model, queryset=None, **kwargs):
    """
        Performs the query on the specified `queryset`
        (defaulting to the `all` queryset of the `model`'s default manager)
        and returns the unique object matching the given
        keyword arguments.  Returns `None` if no match is found.
        Throws a `model.MultipleObjectsReturned` exception
        if more than one match is found.
    """
    if queryset is None:
        queryset = model.objects.all()
    try:
        return queryset.get(**kwargs)
    except model.DoesNotExist:
        return None

这可以用在两种情况下,例如:

obj = get_unique_or_none(Model, **kwargs),如前所述 obj = get_unique_or_none(模型,父。孩子,* * kwargs)

你可以在过滤器中使用exists:

Content.objects.filter(name="baby").exists()
#returns False or True depending on if there is anything in the QS

如果你只想知道它是否存在,这是另一种选择