Python 在Django的自定义管理器中捕获DoesNotExist异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14255125/
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
Catching DoesNotExist exception in a custom manager in Django
提问by Seperman
I have a custom manager for a Django model. I don't seem to be able to catch DoesNotExist exception here. I know how to do it inside the model but it didn't work here:
我有一个 Django 模型的自定义管理器。我似乎无法在这里捕捉到DoesNotExist 异常。我知道如何在模型内部执行此操作,但在这里不起作用:
class TaskManager(models.Manager):
def task_depend_tree(self, *args, **kwargs):
if "id" in kwargs:
try:
task = self.get(id=kwargs["id"])
except DoesNotExist:
raise Http404
Get_object_or_404 doesn't work either. What is wrong here?
Get_object_or_404 也不起作用。这里有什么问题?
采纳答案by Jeff Triplett
Try either using ObjectDoesNotExistinstead of DoesNotExistor possibly self.DoesNotExist. If all else fails, just try and catch a vanilla Exceptionand evaluate it to see it's type().
尝试使用ObjectDoesNotExist代替DoesNotExist或可能使用self.DoesNotExist。如果所有其他方法都失败了,只需尝试捕获一个香草Exception并评估它以查看它的类型()。
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import ObjectDoesNotExist
回答by panchicore
you can use the DoesNotExist from the Manager.model (self.model) instance,
when you say objects = MyManager()you are assigning self.model inside MyManager class.
当您说objects = MyManager()要在 MyManager 类中分配 self.model时,您可以使用来自 Manager.model (self.model) 实例的DoesNotExist。
try:
task = self.get(id=kwargs["id"])
return task
except self.DoesNotExist:
return None
回答by danbal
As panchicore suggested, self.modelis the way to go.
正如 panchicore 所建议的那样,self.model是要走的路。
class TaskManager(models.Manager):
def task_depend_tree(self, *args, **kwargs):
if "id" in kwargs:
try:
task = self.get(id=kwargs["id"])
except self.model.DoesNotExist:
raise Http404
回答by Théo T. Carranza
If you need to implement this on a list method (DRF) using GenericViewSet, and need an empty list to be returned, use this:
如果您需要使用 GenericViewSet 在列表方法 (DRF) 上实现此功能,并且需要返回一个空列表,请使用以下命令:
def list(self, request, *args, **kwargs):
self.get_object() # I use this to trigger the object_permission
try:
queryset = self.queryset.filter(user=(YourModel.objects.get(user=request.user).user))
except YourModel.DoesNotExist:
return Response(YourModel.objects.none())
serializer = YSourModelSerializer(queryset, many=True)
return Response(serializer.data)
回答by KurtS38
I handle the exception this way and it worked.
我以这种方式处理异常并且它起作用了。
from django.core.exceptions import ObjectDoesNotExist
try:
task = self.get(id=kwargs["id"])
except ObjectDoesNotExist as DoesNotExist:
raise Http404

