Django检查相关对象是否存在错误:RelatedObjectDoesNotExist [英] Django check if a related object exists error: RelatedObjectDoesNotExist

查看:221
本文介绍了Django检查相关对象是否存在错误: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆