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")
Run Code Online (Sandbox Code Playgroud)
但我得到错误:
Business.has_related_object()
RelatedObjectDoesNotExist:业务没有客户.
mrt*_*rts 124
使用hasattr(self, 'customers')以避免异常支票在Django文档建议:
def has_related_object(self):
return hasattr(self, 'customers') and self.car is not None
Run Code Online (Sandbox Code Playgroud)
sch*_*ngt 57
这是因为ORM必须转到数据库检查是否customer存在.由于它不存在,它引发了一个例外.
您必须将方法更改为以下内容:
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)
Run Code Online (Sandbox Code Playgroud)
我不知道情况self.car所以我会留给你调整它,如果它需要它.
附注:如果您在具有ForeignKeyField或OneToOneField的模型上执行此操作,则可以执行以下操作以避免数据库查询.
def has_business(self):
return self.business_id is not None
Run Code Online (Sandbox Code Playgroud)
Meh*_*are 10
尽管这是一个老问题,但我认为这对于希望处理此类异常的人很有帮助,特别是当您想要检查 OneToOne 关系时。
我的解决方案是使用ObjectDoesNotExistfrom django.core.exceptions:
from django.core.exceptions import ObjectDoesNotExist
class Business(base):
name = models.CharField(max_length=100, blank=True, null=True)
def has_related_object(self):
try:
self.customers
self.car
return True
except ObjectDoesNotExist:
return False
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)
| 归档时间: |
|
| 查看次数: |
36935 次 |
| 最近记录: |