处理Django对象的最好方法是什么?

时间:2021-04-18 19:36:57

Whenever I do this:

每当我做这个:

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

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

当什么都找不到时,它总是抛出一个错误。我要怎么处理?

7 个解决方案

#1


60  

from django.core.exceptions import ObjectDoesNotExist

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

I'm writing this from memory, so I'm not sure about the exception.

我是凭记忆写的,所以我不确定是否有例外。

#2


20  

Often, it is more useful to use the Django shortcut function get_object_or_404 instead 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错误,如果成功,您的代码将继续。

#3


13  

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

你也可以捕捉到一个通用的不存在。根据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."

#4


7  

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

#5


6  

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 get will raise not only an exception in the case there's no record you're querying for but also when multiple records are found. Using first when there are more than one record might fail your business logic silently by returning the first record.

请注意,两者并不完全相同。Manager方法get不仅会在没有查询记录的情况下引发异常,还会在发现多个记录时引发异常。当有多个记录时,首先使用它可能会通过返回第一个记录而使业务逻辑静默失败。

#6


2  

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

在视图的不同位置处理异常可能非常麻烦。在模型中定义自定义模型管理器怎么样?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

然后在content Model类中包含它

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

#7


1  

Raising a Http404 exception works 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})

#1


60  

from django.core.exceptions import ObjectDoesNotExist

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

I'm writing this from memory, so I'm not sure about the exception.

我是凭记忆写的,所以我不确定是否有例外。

#2


20  

Often, it is more useful to use the Django shortcut function get_object_or_404 instead 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错误,如果成功,您的代码将继续。

#3


13  

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

你也可以捕捉到一个通用的不存在。根据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."

#4


7  

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

#5


6  

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 get will raise not only an exception in the case there's no record you're querying for but also when multiple records are found. Using first when there are more than one record might fail your business logic silently by returning the first record.

请注意,两者并不完全相同。Manager方法get不仅会在没有查询记录的情况下引发异常,还会在发现多个记录时引发异常。当有多个记录时,首先使用它可能会通过返回第一个记录而使业务逻辑静默失败。

#6


2  

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

在视图的不同位置处理异常可能非常麻烦。在模型中定义自定义模型管理器怎么样?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

然后在content Model类中包含它

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

#7


1  

Raising a Http404 exception works 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})

相关文章