在Django中登录用户的配置文件而不重复请求用户很多?

2024-04-24 11:42:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Django编写的应用程序要求我在许多视图中获取UserProfile模型对象(它与标准Django用户对象有一对一的关系)。为了获得用户的配置文件,我在所有不同的视图中重复了很多类似的内容:

user_profile = UserProfile.objects.get(user=request.user)

或者

user_profile = UserProfile.objects.get(user=self.request.user)

我知道好的软件工程原理是说不要重复你自己(DRY),所以我想知道是否有一个好的方法将上面的代码封装在一个单独的方法中,或者是否可以保持原样。你知道吗

提前感谢您的帮助!你知道吗


Tags: 对象django方法用户模型视图应用程序标准
1条回答
网友
1楼 · 发布于 2024-04-24 11:42:28

related name添加到models.py中的用户配置文件

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    about = models.TextField(default='')

然后在views.py中,用

request.user.profile.about = 'abc'
request.user.profile.save()

或者缩短一点

p = request.user.profile
p.about = 'abc'
p.save()

相关问题 更多 >