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

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

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


当前回答

我也面临着同样的问题。编写和读取try是很困难的——除非你想从模型中获取一个元素,比如@Arthur Debert的回答。因此,我的解决方案是创建一个由模型继承的Getter类:

class Getter:
    @classmethod
    def try_to_get(cls, *args, **kwargs):
        try:
            return cls.objects.get(**kwargs)
        except Exception as e:
            return None

class MyActualModel(models.Model, Getter):
    pk_id = models.AutoField(primary_key=True)
    ...

通过这种方式,我可以得到MyActualModel或None的实际元素:

MyActualModel.try_to_get(pk_id=1)

其他回答

我们可以使用Django内置的异常,附加到模型命名为。doesnotexist。因此,我们不需要导入ObjectDoesNotExist异常。

而不是做:

from django.core.exceptions import ObjectDoesNotExist

try:
    content = Content.objects.get(name="baby")
except ObjectDoesNotExist:
    content = None

我们可以这样做:

try:
    content = Content.objects.get(name="baby")
except Content.DoesNotExist:
    content = None

如果发生这样的事呢?

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

如果你想要一个简单的单行解决方案,不涉及异常处理、条件语句或Django 1.6+的要求,可以这样做:

x = next(iter(SomeModel.objects.filter(foo='bar')), None)

我使用的是Django 2.2.16。这就是我解决这个问题的方法:

from typing import Any

from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models.base import ModelBase
from django.db.models.manager import Manager


class SManager(Manager):
    def get_if_exist(self, *args: Any, **kwargs: Any):
        try:
            return self.get(*args, **kwargs)
        except ObjectDoesNotExist:
            return None


class SModelBase(ModelBase):
    def _prepare(cls):
        manager = SManager()
        manager.auto_created = True
        cls.add_to_class("objects", manager)

        super()._prepare()

    class Meta:
        abstract = True


class SModel(models.Model, metaclass=SModelBase):
    managers = False

    class Meta:
        abstract = True

之后,在每个模型中,你只需要导入:

from custom.models import SModel


class SUser(SModel):
    pass

在视图中,你可以这样调用:

SUser.objects.get_if_exist(id=1)

这是Django get_object_or_404方法的一个副本,只是该方法返回None。当我们必须使用only()查询来只检索某些字段时,这是非常有用的。该方法可以接受模型或查询集。

from django.shortcuts import _get_queryset


def get_object_or_none(klass, *args, **kwargs):
    """
    Use get() to return an object, or return None if 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.
    Like with QuerySet.get(), MultipleObjectsReturned is raised if more than
    one object is found.
    """
    queryset = _get_queryset(klass)
    if not hasattr(queryset, 'get'):
        klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
        raise ValueError(
            "First argument to get_object_or_none() must be a Model, Manager, "
            "or QuerySet, not '%s'." % klass__name
        )
    try:
        return queryset.get(*args, **kwargs)
    except queryset.model.DoesNotExist:
        return None