gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:26:37 31 4
gpt4 key购买 nike

我的模型中有一个方法 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")

但我得到了错误:

Business.has_related_object()

RelatedObjectDoesNotExist: Business has no customer.

最佳答案

使用 hasattr(self, 'customers') 避免异常检查为 recommended in Django docs :

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

关于python - Django检查相关对象是否存在错误: RelatedObjectDoesNotExist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27064206/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com