Django - 如何区分数据库中的用户?

Django - How to differentiate between users in the database?

我正在为我的公司构建一个 Django 服务器,但我仍然不熟悉某些流程。我敢肯定这非常简单,我只是完全不知道它是如何工作的。

如何区分用户数据以免混淆?

如果 Jill 是一个用户并且她请求一页她的个人资料数据,我如何不向她发送 Jack 的个人资料数据,尤其是涉及多个模型时?

例如,视图中的代码如下所示:

def display_profile(request)
    profile = Profile.objects.get(???) # What do I put in here?

我明白我能做到:

def display_profile(request, user)
    profile = Profile.objects.get(user_id=user)

但这不是我的设计意图。

提前谢谢你。

在您的 Django 视图中,您可以使用 request.user 访问当前用户。

因此,如果您想获得与当前登录用户匹配的 Profile 实例,只需执行如下查询:

profile = Profile.objects.get(user=request.user)

这假设您的配置文件模型中有一个 user 外键字段(或 OneToOne)。

作为documented

Django uses sessions and middleware to hook the authentication system into request objects.

These provide a request.user attribute on every request which represents the current user. If the current user has not logged in, this attribute will be set to an instance of AnonymousUser, otherwise it will be an instance of User.

因此在您的情况下(未调用通知字段 user_id )

profile = Profile.objects.get(user=user)