Make a return oneToOneField No in django

I have a django application with the following model:

class A(models.Model): ... 

And I added a new model that has OneToOne's relationship with A, for example:

 class B(models.Model): a = models.OneToOneField(A) 

As you can see, not every instance of A should have a relationship with B. However, when I try to query A for the existence of a related model B, for example:

 instanceOfA.b 

I get:

 DoesNotExist: B matching query does not exist. 

Is there a way to make this request return None without adding a property to my model A. I know this almost identical question , but, unfortunately, it did not receive the accepted answer, and existing ones suggest changing A.

I am currently using:

  if hasattr(instanceOfA, b): ... 

But this is not very clean.

+4
source share
1 answer

You can set the method to A, for example.

 class A(object): # default stuff def get_b(self): return getattr(self, 'b', None) 

Or more explicit

 class A(object): def get_b(self): try: return self.b except Foobar.DoesNotExist: return None 

This is covered by the Django function bit here

+4
source

All Articles