如何导入Django DoesNotExistexception?

我试图创build一个UnitTest来validation对象已被删除。

from django.utils import unittest def test_z_Kallie_can_delete_discussion_response(self): ...snip... self._driver.get("http://localhost:8000/questions/3/want-a-discussion") self.assertRaises(Answer.DoesNotExist, Answer.objects.get(body__exact = '<p>User can reply to discussion.</p>')) 

我不断收到错误:

 DoesNotExist: Answer matching query does not exist. 

您不需要导入它 – 因为您已经正确书写, DoesNotExist是模型本身的属性,在这种情况下, Answer

你的问题在于,在传递给assertRaises之前,你正在调用get方法 – 这会引发exception。 您需要从可调用对象中分离参数,如unit testing文档中所述 :

 self.assertRaises(Answer.DoesNotExist, Answer.objects.get, body__exact='<p>User can reply to discussion.</p>') 

或更好:

 with self.assertRaises(Answer.DoesNotExist): Answer.objects.get(body__exact='<p>User can reply to discussion.</p>') 

你也可以从django.core.exceptions导入ObjectDoesNotExist ,如果你想要一个通用的,与模型无关的方法来捕获exception:

 from django.core.exceptions import ObjectDoesNotExist try: SomeModel.objects.get(pk=1) except ObjectDoesNotExist: print 'Does Not Exist!' 

DoesNotExist始终是不存在的模型的属性。 在这种情况下,它将是Answer.DoesNotExist

有一点需要注意的是, assertRaises的第二个参数需要是可调用的,而不仅仅是一个属性。 例如,我对这个声明有困难:

 self.assertRaises(AP.DoesNotExist, self.fma.ap) 

但这工作得很好:

 self.assertRaises(AP.DoesNotExist, lambda: self.fma.ap) 
 self.assertFalse(Answer.objects.filter(body__exact='<p>User...discussion.</p>').exists()) 

这是我如何做这样的testing。

 from foo.models import Answer def test_z_Kallie_can_delete_discussion_response(self): ...snip... self._driver.get("http://localhost:8000/questions/3/want-a-discussion") try: answer = Answer.objects.get(body__exact = '<p>User can reply to discussion.</p>')) self.fail("Should not have reached here! Expected no Answer object. Found %s" % answer except Answer.DoesNotExist: pass # all is as expected