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

后端 未结 6 1411
失恋的感觉
失恋的感觉 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

    This custom django field will do exactly what you want:

    class SingleRelatedObjectDescriptorReturnsNone(SingleRelatedObjectDescriptor):
        def __get__(self, *args, **kwargs):
            try:
                return super(SingleRelatedObjectDescriptorReturnsNone, self).__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
    

    To use it:

    class Breakfast(models.Model):
        pass
        # other fields
    
    class Egg(m.Model):
        breakfast = OneToOneOrNoneField(Breakfast, related_name="egg")
    
    breakfast = Breakfast()
    assert breakfast.egg == None
    

提交回复
热议问题