14

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

Prometheus
  • 32,405
  • 54
  • 166
  • 302

1 Answers1

16

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.

Community
  • 1
  • 1
Tom
  • 22,301
  • 5
  • 63
  • 96
  • 1
    For the record, the exceptions being raised are `Customer.DoesNotExist` in the first case and `Car.DoesNotExist` in the second. – bruno desthuilliers Nov 21 '14 at 16:03
  • Is there a function that returns a boolean that I can call instead of catching the error? like ```model.DoesExists(other_model)``` – Jeremy Dec 18 '14 at 05:52
  • 4
    just realized that I could call hasattr on it... so nevermind – Jeremy Dec 18 '14 at 05:55
  • @JeremyCraigMartinez ohh yaaa my problem fixed by simply call `hasattr`, thanks! – Adiyat Mubarak Jul 07 '15 at 02:18
  • @ИскренСтаниславов - what kind of test and what happens instead? – Tom Oct 05 '17 at 14:22
  • @ИскренСтаниславов it's tough to follow that code (maybe put it in a pastebin?) but what's happening instead? This doesn't seem to be a 1:1 match to what was discussed in this question. Maybe post a new question and tag me? – Tom Oct 05 '17 at 18:04
  • @ИскренСтаниславов I think I get what you were saying now: this code didn't work for you, but that's because `RelatedObjectDoesNotExist` isn't a child of `DoesNotExist` (I'm guessing). From the links in my original answer, it looks like `ObjectDoesNotExist` is the parent of both? – Tom Oct 06 '17 at 14:15
  • I deleted my comments and added a suggestion for django unittesting – Искрен Станиславов Oct 06 '17 at 14:23