Python 如何在 Django 中捕获 MultipleObjectsReturned 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32172934/
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-19 11:10:29  来源:igfitidea点击:

how to catch the MultipleObjectsReturned error in django

pythondjangoexception

提问by Tom

Is it possible to catch the MultipleObjectsReturnederror in Django?

是否有可能MultipleObjectsReturned在 Django 中捕获错误?

I do a searchquery and if there are more than one objects I want that the first in the list will be taken so I tried this:

我做了一个搜索查询,如果有多个对象,我想要列表中的第一个将被采用,所以我尝试了这个:

try:
    Location.objects.get(name='Paul')
except MultipleObjectsReturned:
    Location.objects.get(name='Paul')[0]

However, it exists in the docthough

然而,它存在于文档虽然

global variable MultipleObjectsReturned does not exist

全局变量 MultipleObjectsReturned 不存在

采纳答案by veggie1

This isn't the best practice. You can technically do this without using exceptions. Did you intend to use Locationand Carin this example?

这不是最佳做法。从技术上讲,您可以在不使用异常的情况下执行此操作。您是否打算在此示例中使用LocationCar

You can do this:

你可以这样做:

Location.objects.filter(name='Paul').order_by('id').first()

I strongly suggest you read the Django QuerySet API reference.

我强烈建议您阅读 Django QuerySet API 参考。

https://docs.djangoproject.com/en/1.8/ref/models/querysets/

https://docs.djangoproject.com/en/1.8/ref/models/querysets/

To answer your question about where the exception exists -- you can always access these QuerySet exceptions on the model itself. E.g. Location.DoesNotExistand Location.MultipleObjectsReturned. You don't need to import them if you already have the model imported.

要回答有关异常存在位置的问题 - 您始终可以在模型本身上访问这些 QuerySet 异常。例如Location.DoesNotExistLocation.MultipleObjectsReturned。如果您已经导入了模型,则不需要导入它们。

回答by rofls

Use a filter:

使用过滤器:

Location.objects.filter(name='Paul').first()

Or import the exception:

或者导入异常:

from django.core.exceptions import MultipleObjectsReturned
...
try:
    Location.objects.get(name='Paul')
except MultipleObjectsReturned:
    Location.objects.filter(name='Paul').first()

回答by Vaseem Ahmed Khan

This is more pythonic way to do it.

这是一种更pythonic的方式来做到这一点。

try:
    Location.objects.get(name='Paul')
except Location.MultipleObjectsReturned:
    Location.objects.filter(name='Paul')[0]