[Answer]-How to check object relation is populated without catching DoesNotExist

1👍

If I understand this correctly, firstly the attribute “related_name” is used to refer the current object from the reversed foreign key object, so the model definition should be something like :

class A:
   ...

class B:
    a = models.OneToOneField(A, related_name='alias_for_b')
    name = models.TextField(...)

and the validation code could be simply:

if hasattr(a, 'alias_for_b'):
    print(a.b) or print(a.alias_for_b)

Hope this helps !!

0👍

Let’s say you have your instance of A a. As you correctly say you can access the related instance of B b with something like print(a.b) (Python 3 syntax). If it’s possible that there will be no related item and you don’t want the user to get an error then you need to wrap that call to b up in something. Something like:

try:
    print(a.b)
except:
    print('Nothing to see here')

That checks for b‘s presence before trying to present it, and won’t do so if it’s not there.

Alternatively, you could approach this from the other direction. Given an instance a you could look up B.objects.filter(your_relation_name=a). That way won’t involve any error catching, just a blank queryset if no such b exists.

Leave a comment