Django RelatedObjectDoesNotExist错误

Pro*_*eus 12 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")
Run Code Online (Sandbox Code Playgroud)

错误

RelatedObjectDoesNotExist Business没有客户.

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

Tom*_*Tom 13

你陷入困境,except Business.DoesNotExist但这并不是被抛出的例外.根据这个SO答案,你想要捕捉一般的DoesNotExist例外.

编辑:请参阅下面的评论:实际的异常被捕获,DoesNotExist因为他们继承DoesNotExist.你最好捕获真正的异常,而不是压制DoesNotExist所涉及的模型中的任何和所有异常.

  • 刚才意识到我可以在上面调用hasattr ......所以没关系 (3认同)