I have two models like this:
class Collar(models.Model):
num_tags = models.BigIntegerField()
class Dog(models.Model):
num_legs = models.BigIntegerField()
collar = models.OneToOneField(Collar,null=True,blank=True)
Whenever I try to do something like:
dog = Dog.objects.all()[0]
if dog.collar:
#do something ...
I get a DoesNotExist Error on the line: if dog.collar.
How can I tell Django that this is ok? That a collar won’t always exist and I want to check for its existence without triggering an error?
Use a
try..exceptblock:Also, never assume that
all()will always return something. In ideal circumstances, sure, but life is never ideal. You need to catch the potentialIndexErrorwith a statement like that, and have a contingency plan in place: