Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make reverse OneToOneField return None in django

I've got a django app with the following model:

class A(models.Model):
    ...

And I've added a new model which has a OneToOne relationship with A, like so:

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 B model, like:

instanceOfA.b

I get:

DoesNotExist: B matching query does not exist.

Is there a way I can make this query return None without adding a property to my A model. I'm aware of this almost identical question but sadly it's got no accepted answer and the existing ones suggest modifying A.

I'm currently using:

 if hasattr(instanceOfA, b):
        ...

But it doesn't feel very clean.

like image 817
kirbuchi Avatar asked May 02 '13 08:05

kirbuchi


1 Answers

You could set a method on A, e.g.

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 a Django feature ticket here

like image 102
Hedde van der Heide Avatar answered Sep 23 '22 19:09

Hedde van der Heide