Python 处理 Django 的 objects.get 的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4353147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:23:04  来源:igfitidea点击:

What's the best way to handle Django's objects.get?

pythondjango

提问by TIMEX

Whenever I do this:

每当我这样做时:

thepost = Content.objects.get(name="test")

It always throws an error when nothing is found. How do I handle it?

当没有找到任何东西时,它总是会引发错误。我该如何处理?

采纳答案by Some programmer dude

try:
    thepost = Content.objects.get(name="test")
except Content.DoesNotExist:
    thepost = None

Use the model DoesNotExist exception

使用模型DoesNotExist 异常

回答by Rob Golding

Often, it is more useful to use the Django shortcut function get_object_or_404instead of the API directly:

通常,直接使用 Django 快捷功能get_object_or_404而不是 API更有用:

from django.shortcuts import get_object_or_404

thepost = get_object_or_404(Content, name='test')

Fairly obviously, this will throw a 404 error if the object cannot be found, and your code will continue if it is successful.

很明显,如果找不到对象,这将引发 404 错误,如果成功,您的代码将继续。

回答by Anurag Uniyal

Catch the exception

捕捉异常

try:
    thepost = Content.objects.get(name="test")
except Content.DoesNotExist:
    thepost = None

alternatively you can filter, which will return a empty list if nothing matches

或者,您可以过滤,如果没有匹配项,它将返回一个空列表

posts = Content.objects.filter(name="test")
if posts:
    # do something with posts[0] and see if you want to raise error if post > 1

回答by zobbo

You can also catch a generic DoesNotExist. As per the docs at http://docs.djangoproject.com/en/dev/ref/models/querysets/

您还可以捕获通用的DoesNotExist。根据http://docs.djangoproject.com/en/dev/ref/models/querysets/ 上的文档

from django.core.exceptions import ObjectDoesNotExist
try:
    e = Entry.objects.get(id=3)
    b = Blog.objects.get(id=1)
except ObjectDoesNotExist:
    print "Either the entry or blog doesn't exist."

回答by Banjer

Raising a Http404 exceptionworks great:

提高一个HTTP404异常的伟大工程:

from django.http import Http404

def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})

回答by Adil Malik

Handling exceptions at different points in your views could really be cumbersome..What about defining a custom Model Manager, in the models.py file, like

在视图中的不同点处理异常可能真的很麻烦..如何在 models.py 文件中定义自定义模型管理器,例如

class ContentManager(model.Manager):
    def get_nicely(self, **kwargs):
        try:
            return self.get(kwargs)
        except(KeyError, Content.DoesNotExist):
            return None

and then including it in the content Model class

然后将其包含在内容模型类中

class Content(model.Model):
    ...
    objects = ContentManager()

In this way it can be easily dealt in the views i.e.

这样就可以很容易地在视图中处理,即

post = Content.objects.get_nicely(pk = 1)
if post != None:
    # Do something
else:
    # This post doesn't exist

回答by Rafael Valverde

Another way of writing:

另一种写法:

try:
    thepost = Content.objects.get(name="test")
except Content.DoesNotExist:
    thepost = None

is simply:

很简单:

thepost = Content.objects.filter(name="test").first()

Note that the two are not strictly the same. Manager method getwill raise not only an exception in the case there's no recordyou're querying for but also when multiple recordsare found. Using firstwhen there are more than one record might fail your business logic silently by returning the first record.

请注意,两者并不严格相同。Manager 方法get不仅会在没有您要查询的记录的情况下引发异常,还会在找到多条记录时引发异常。使用first时,有一个以上的记录可能通过返回的第一条记录失败默默你的业务逻辑。