'Django check if a related object exists error: RelatedObjectDoesNotExist
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.
Solution 1:[1]
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
Solution 2:[2]
Although it's an old question, I thought this can be helpful for someone looking to handle this type of exception, especially when you want to check for OneToOne relations.
My solution is to use ObjectDoesNotExist from django.core.exceptions:
from django.core.exceptions import ObjectDoesNotExist
class Business(base):
name = models.CharField(max_length=100, blank=True, null=True)
def has_related_object(self):
try:
self.customers
self.car
return True
except ObjectDoesNotExist:
return False
class Customer(base):
name = models.CharField(max_length=100, blank=True, null=True)
person = models.OneToOneField('Business', related_name="customer")
Solution 3:[3]
You probably had created the user before while debuging and has no profile, so even after now coding the automation in, they still have no profile try the code below in your signal.py file, then create a superuser, log in as the super user and then add the first account's profile from there. That worked for me...
@receiver(post_save, sender=User, dispatch_uid='save_new_user_profile')
def save_profile(sender, instance, created, **kwargs):
user = instance
if created:
profile = UserProfile(user=user)
profile.save()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | phoenix |
| Solution 2 | Mehdi Zare |
| Solution 3 | JacksonPro |
