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

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

而不是DoesNotExist,我怎么能去是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)

其他回答

Maybe更好用:

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

下面是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)

这是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

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

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

没有“内置”的方法可以做到这一点。Django每次都会抛出DoesNotExist异常。 在python中,处理这个问题的惯用方法是将其封装在try catch中:

try:
    go = SomeModel.objects.get(foo='bar')
except SomeModel.DoesNotExist:
    go = None

我所做的就是将模型子类化。Manager,创建一个类似于上面代码的safe_get,并将该Manager用于我的模型。这样你就可以写:sommodel .objects.safe_get(foo='bar')。