I\'ve got a Django class like this:
class Breakfast(m.Model):
# egg = m.OneToOneField(Egg)
...
class Egg(m.Model):
breakfast = m.OneToOneField(Break
Django 1.10 solution as by Fedor at accepted answer:
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields.related import OneToOneField
from django.db.models.fields.related_descriptors import ReverseOneToOneDescriptor
class ReverseOneToOneOrNoneDescriptor(ReverseOneToOneDescriptor):
def __get__(self, instance, cls=None):
try:
return super(ReverseOneToOneOrNoneDescriptor, self).__get__(instance=instance, cls=cls)
except ObjectDoesNotExist:
return None
class OneToOneOrNoneField(models.OneToOneField):
"""A OneToOneField that returns None if the related object doesn't exist"""
related_accessor_class = ReverseOneToOneOrNoneDescriptor