Check if OneToOneField is None in Django

后端 未结 8 1645
走了就别回头了
走了就别回头了 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:41

    I am using a combination of has_attr and is None:

    class DriverLocation(models.Model):
        driver = models.OneToOneField(Driver, related_name='location', on_delete=models.CASCADE)
    
    class Driver(models.Model):
        pass
    
        @property
        def has_location(self):
            return not hasattr(self, "location") or self.location is None
    

提交回复
热议问题