Django检查相关对象是否存在错误:RelatedObjectDoesNotExist [英] Django check if a related object exists error: RelatedObjectDoesNotExist
问题描述
我的模型中有一个方法 has_related_object
,需要检查是否存在相关对象
I have a method has_related_object
in my model that needs to check if a related object exists
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")
但是我得到了错误:
Business.has_related_object()
Business.has_related_object()
RelatedObjectDoesNotExist:业务没有客户.
RelatedObjectDoesNotExist: Business has no customer.
推荐答案
这是因为ORM必须去数据库检查 customer
是否存在.由于不存在,因此引发异常.
This is because the ORM has to go to the database to check to see if customer
exists. Since it doesn't exist, it raises an exception.
您必须将方法更改为以下内容:
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)
我不了解 self.car
的情况,因此如果需要它,我会留给您进行调整.
I don't know the situation with self.car
so I'll leave it to you to adjust it if it needs it.
旁注:如果您在具有 ForeignKeyField
或 OneToOneField
的 Model
上执行此操作,则可以通过以下操作作为快捷方式避免数据库查询.
Side note:
If you were doing this on a Model
that has the ForeignKeyField
or OneToOneField
on it, you would be able to do the following as a shortcut to avoid the database query.
def has_business(self):
return self.business_id is not None
这篇关于Django检查相关对象是否存在错误:RelatedObjectDoesNotExist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!