Django: Return 'None' from OneToOneField if related object doesn't exist?

后端 未结 6 1395
失恋的感觉
失恋的感觉 2021-02-04 01:48

I\'ve got a Django class like this:

class Breakfast(m.Model):
    # egg = m.OneToOneField(Egg)
    ...

class Egg(m.Model):
    breakfast = m.OneToOneField(Break         


        
6条回答
  •  孤城傲影
    2021-02-04 02:04

    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
    

提交回复
热议问题