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.

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


Need Your Help

Enter PEM pass phrase just once

python twisted python-2.7

I have a loop that that run every 30 sec, connects to a SSL server (reactor.connectSSL()), send a message (self.transport.write(msg)) and then disconnect (self.transport.loseConnection()).

C# cast generic T in abstract class<T> to dynamic

c# generics dynamic

This is what I want to do in C# (within class Helper - without generic arguments),

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.