Check if OneToOneField is None in Django

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

    To check if the (OneToOne) relation exists or not, you can use the hasattr function:

    if hasattr(request.user, 'type1profile'):
        # do something
    elif hasattr(request.user, 'type2profile'):
        # do something else
    else:
        # do something else
    

提交回复
热议问题