首页 > 解决方案 > 在 djago 中,如果您扩展用户模型并使用配置文件模型

问题描述

如果我们想要来自配置文件模型的移动属性,我们如何使用下面的代码?

user.profile.mobile

但是配置文件类有用户引用,这意味着可以像这样访问用户名

profile.user.username

标签: djangodjango-models

解决方案


定义一个related_name调用反向访问器:

class Profile(models.Model):
    user_name = models.OneToOneField(to= User,on_delete=CASCADE,related_name='profile')
    mobile = models.PositiveIntegerField(null = True,blank = True)

打印(request.user.profile.mobile)


推荐阅读