Check if OneToOneField is None in Django

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

    in case you have the Model

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

    And you just need to know for any User that UserProfile exists/or not - the most efficient way from the database point of view to use exists query.

    Exists query will return just boolean, rather than reverse attribute access like hasattr(request.user, 'type1profile') - which will generate get query and return full object representation

    To do it - you need to add a property to the User model

    class User(AbstractBaseUser)
    
    @property
    def has_profile():
        return UserProfile.objects.filter(user=self.pk).exists()
    

提交回复
热议问题