Python Django 检查相关对象是否存在错误:RelatedObjectDoesNotExist

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27064206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:23:30  来源:igfitidea点击:

Django check if a related object exists error: RelatedObjectDoesNotExist

pythondjango

提问by Prometheus

I have a method has_related_objectin my model that needs to check if a related object exists

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

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

  def has_related_object(self):
        return (self.customers is not None) and (self.car is not None)


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

But I get the error:

但我收到错误:

Business.has_related_object()

RelatedObjectDoesNotExist: Business has no customer.

Business.has_related_object()

RelatedObjectDoesNotExist:企业没有客户。

采纳答案by schillingt

This is because the ORM has to go to the database to check to see if customerexists. Since it doesn't exist, it raises an exception.

这是因为 ORM 必须去数据库检查是否customer存在。由于它不存在,它引发了一个异常。

You'll have to change your method to the following:

您必须将方法更改为以下内容:

def has_related_object(self):
    has_customer = False
    try:
        has_customer = (self.customers is not None)
    except Customer.DoesNotExist:
        pass
    return has_customer and (self.car is not None)

I don't know the situation with self.carso I'll leave it to you to adjust it if it needs it.

我不知道情况,self.car所以如果需要,我会留给你调整。

Side note: If you were doing this on a Modelthat has the ForeignKeyFieldor OneToOneFieldon it, you would be able to do the following as a shortcut to avoid the database query.

旁注:如果您在Model具有ForeignKeyField或 的对象OneToOneField上执行此操作,则可以执行以下操作作为避免数据库查询的快捷方式。

def has_business(self):
    return self.business_id is not None

回答by mrts

Use hasattr(self, 'customers')to avoid the exception check as recommended in Django docs:

使用hasattr(self, 'customers')以避免异常支票在Django文档建议

def has_related_object(self):
    return hasattr(self, 'customers') and self.car is not None