I have a one to one relationship defined on a model. Let's call the parent model A and the related model B. B will not always exist. When I'm interacting with an instance of A how can I determine if B exists without having to catch DoesNotExist? When I attempt to access an instance of B (e.g. print a.b
) I receive a DoesNotExist exception. When there is a DB row corresponding to the relation it works. This is on django 1.5.
Simplified model definition off the top of my head (not tested in this form):
class A:
...
class B:
a = models.OneToOneField(A, related_name='a')
name = models.TextField(...)
fields = ['b__name']
a = A.object.filter(pk=id).selected_related(*fields)
print(a.b)
Table B has a foreign key of a_id.
My reason for the question was to determine if there was a cleaner way to do this via an API rather than catching an exception.