Check if OneToOneField is None in Django

后端 未结 8 1647
走了就别回头了
走了就别回头了 2021-01-30 10:04

I have two models like this:

class Type1Profile(models.Model):
    user = models.OneToOneField(User, unique=True)
    ...


class Type2Profile(models.Model):
            


        
8条回答
  •  清歌不尽
    2021-01-30 10:42

    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
    

提交回复
热议问题