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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With