Django RelatedObjectDoesNotExist error

Question:

I cannot see to get this to work…

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):
    has_customer = False
    has_car = False

    try:
        has_customer = (self.customer is not None)
    except Business.DoesNotExist:
        pass

    try:
        has_car = (self.car.park is not None)
    except Business.DoesNotExist:
        pass

    return has_customer and has_car



class Customer(base):
      name =  models.CharField(max_length=100, blank=True, null=True)
      person = models.OneToOneField('Business', related_name="customer")

Error

RelatedObjectDoesNotExist Business has no customer.

I need to check if these related objects exist but from within the business object method

Asked By: Prometheus

||

Answers:

You’re trapping except Business.DoesNotExist but that’s not the exception that’s being thrown. Per this SO answer you want to catch the general DoesNotExist exception instead.

EDIT: see comment below: the actual exceptions are being caught by DoesNotExist because they inherit from DoesNotExist. You’re better off trapping the real exception rather than suppressing any and all DoesNotExist exceptions from the involved models.

Answered By: Tom

EDIT: see comment below: the actual exceptions are being caught by DoesNotExist because they inherit from DoesNotExist. You’re better off trapping the real exception rather than suppressing any and all DoesNotExist exceptions

Answered By: user20791242
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.