I have two models like this:
class Type1Profile(models.Model):
user = models.OneToOneField(User, unique=True)
...
class Type2Profile(models.Model):
One of the smart approaches will be to add custom field OneToOneOrNoneField and use it [works for Django >=1.9]
from django.db.models.fields.related_descriptors import ReverseOneToOneDescriptor
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
class SingleRelatedObjectDescriptorReturnsNone(ReverseOneToOneDescriptor):
def __get__(self, *args, **kwargs):
try:
return super().__get__(*args, **kwargs)
except ObjectDoesNotExist:
return None
class OneToOneOrNoneField(models.OneToOneField):
"""A OneToOneField that returns None if the related object doesn't exist"""
related_accessor_class = SingleRelatedObjectDescriptorReturnsNone
def __init__(self, *args, **kwargs):
kwargs.setdefault('null', True)
kwargs.setdefault('blank', True)
super().__init__(*args, **kwargs)
Implementation
class Restaurant(models.Model): # The class where the one-to-one originates
place = OneToOneOrNoneField(Place)
serves_hot_dogs = models.BooleanField()
serves_pizza = models.BooleanField()
Usage
r = Restaurant(serves_hot_dogs=True, serves_pizza=False)
r.place # will return None