2015-08-24 62 views
5

是否有可能在Django中发现MultipleObjectsReturned错误?如何捕捉django中的MultipleObjectsReturned错误

我做了SEARCHQUERY,如果有一个以上的对象我想,在列表中第一个将采取所以我尝试这样的:

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

然而,它存在于doc虽然

全局变量MultipleObjectsReturned不存在

+1

如果我没有弄错,例外是模型的推理。由于该变量不存在错误似乎导致我相信如此。 – dylan7

+0

https://docs.djangoproject.com/en/1.8/ref/exceptions/#multipleobjects返回 – Gocht

+1

但是,我建议使用过滤器,它返回一个查询集,然后你可以采用索引的查询集中的第一个项目。获取是用于返回1个实际对象。所以你不必处理错误检查。 – dylan7

回答

5

这是不是最好的做法。你可以在技术上做到这一点,而不使用例外。在这个例子中你打算使用LocationCar吗?

你可以这样做:

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

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

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

要回答你关于在异常存在的问题 - 你可以随时访问模型本身这些查询集例外。例如。 Location.DoesNotExistLocation.MultipleObjectsReturned。如果您已经导入模型,则不需要导入它们。

+0

是啊真的!对不起,这意味着两次都是。为什么使用例外不是最佳做法? – Tom

+0

然后你可能想要的只是'Location.objects.filter(name ='Paul')。order_by('id')。first()'。如果没有该名称的记录,它将返回None。我更新了答案。在这种情况下使用例外是不必要的。不会引发异常,您仍然可以拥有一条快乐的道路而不会产生任何错误。 – veggie1

+0

我明白了,好的,谢谢! – Tom

15

使用过滤器:

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

或进口除外:

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

完美作品,谢谢!忘记导入例外 – Tom

+0

**注意**:'Location.objects.get(name ='Paul')[0]'会再次引发'MultipleObjectsReturned'。使用'Location.objects.filter(name ='Paul')。first()'来代替。 – jojo

8

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

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

你的意思是'filter',但至少它确实回答了如何捕捉异常。 – RemcoGerlich

+0

@RemcoGerlich是它根据查询过滤或返回对象。获取返回对象,而.filter返回queryset。 –

+0

@VaseemAhmedKhan答案应该更新为'Location.objects.filter(name ='Paul')[0]',否则except块将导致抛出相同的异常。你需要一个查询集,因为它包含返回_which_对象的逻辑,例如'Location.objects.get(name ='Paul')。order_by('age')[0]'将返回数据库中最年轻的Paul。根据您的业务逻辑,这是您如何返回正确的保罗。 – AlanSE