【问题标题】:Django RelatedObjectDoesNotExist errorDjango RelatedObjectDoesNotExist 错误
【发布时间】:2015-01-19 19:24:04
【问题描述】:

我看不到让它工作......

我的模型中有一个方法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 没有客户。

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

【问题讨论】:

  • 您的问题是什么?谢谢。
  • 我需要检查这些相关对象是否存在但来自业务对象方法

标签: python django


【解决方案1】:

您正在捕获except Business.DoesNotExist,但这不是抛出的异常。根据this SO answer,您想捕获一般的DoesNotExist 异常。

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

【讨论】:

  • 记录在案,引发的异常是第一种情况下的Customer.DoesNotExist 和第二种情况下的Car.DoesNotExist
  • 是否有返回布尔值的函数,我可以调用它而不是捕获错误?喜欢model.DoesExists(other_model)
  • 刚刚意识到我可以调用 hasattr... 所以没关系
  • @JeremyCraigMartinez 哦,我的问题只需致电hasattr 即可解决,谢谢!
  • @ИскренСтаниславов - 什么样的测试,会发生什么?
猜你喜欢
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 2015-01-19
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
  • 1970-01-01
相关资源
最近更新 更多