Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django check if a related object exists error: RelatedObjectDoesNotExist

Tags:

python

django

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") 

But I get the error:

Business.has_related_object()

RelatedObjectDoesNotExist: Business has no customer.

like image 470
Prometheus Avatar asked Nov 21 '14 14:11

Prometheus


1 Answers

Use hasattr(self, 'customers') to avoid the exception check as recommended in Django docs:

def has_related_object(self):     return hasattr(self, 'customers') and self.car is not None 
like image 54
mrts Avatar answered Sep 17 '22 05:09

mrts