Django RelatedObjectDoesNotExist错误

时间:2014-11-21 15:35:00

标签: python django

我看不到让它发挥作用......

我的模型中有一个方法has_related_object,需要检查相关对象是否存在...

class Business(base):
      name =  models.CharField(max_length=100, blank=True, null=True)


  def has_related_object(self):
    has_customer = False
    has_car = False

    try:
        has_customer = (self.customer is not None)
    except Business.DoesNotExist:
        pass

    try:
        has_car = (self.car.park is not None)
    except Business.DoesNotExist:
        pass

    return has_customer and has_car



class Customer(base):
      name =  models.CharField(max_length=100, blank=True, null=True)
      person = models.OneToOneField('Business', related_name="customer")

错误

  

RelatedObjectDoesNotExist Business没有客户。

我需要检查这些相关对象是否存在但是来自业务对象方法

1 个答案:

答案 0 :(得分:12)

你正在诱捕except Business.DoesNotExist,但这并不是被抛出的例外。每this SO answer您想要捕获常规DoesNotExist例外。

编辑:请参阅下面的评论:DoesNotExist抓住了实际的异常,因为它们是从DoesNotExist继承的。您最好不要捕获真正的异常,而不是从相关模型中抑制任何和所有DoesNotExist异常。