Fix Python – Django check if a related object exists error: RelatedObjectDoesNotExist


Asked By – Prometheus

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 ( 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:


RelatedObjectDoesNotExist: Business has no customer.

Now we will see solution for issue: Django check if a related object exists error: RelatedObjectDoesNotExist


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
        has_customer = (self.customers is not None)
    except Customer.DoesNotExist:
    return has_customer and ( is not None)

I don’t know the situation with so I’ll leave it to you to adjust it if it needs it.

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

This question is answered By – schillingt

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0