数据如何连接到特定的用户 ID?

发布于 2024-12-24 02:24:34 字数 178 浏览 3 评论 0原文

我是 Django 和 python 的新手。我已经完成了登录表单,但我需要知道。如何将页面内容与用户联系起来。 例如:这是一个问答网站。当您登录时,它会显示个人资料页面,其中包含用户之前提出的问题。数据如何链接到模型中的特定用户 ID? 可以使用 User 对象来完成吗?如果是这样,您能给我一些简单的脚本示例吗?

谢谢。

I'm new to Django and python. I've done login forms but I need to know. How can I connect the contents of the page with the user.
For example: It's a Q&A site. When you logged in, It shows profile page with the questions that user asked before. How the datas are linked to the specific user ID in the model?
Can it be done using the User object? If so, could you give me some simple example with the script?

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落日海湾 2024-12-31 02:24:34

“属于”用户的任何内容都应该具有 ForeignKeyManyToManyField(取决于该对象是由一个用户还是多个用户拥有)到 User< /代码> 就可以了。然后,您可以根据用户过滤模型:

SomeModel.objects.filter(user=some_user)
# where `user` is the name of your foreign key field

或者您可以通过反向关系通过用户访问模型,例如:

class SomeModel(models.Model):
    ...
    user = models.ForeignKey(User)

# Later ...

some_user.somemodel_set.all()

第二种方法更为典型,因为您通常已经从请求中获得了用户,因此在您看来,您只需执行以下操作:

somemodels = request.user.somemodel_set.all()

获取属于当前登录用户的所有 SomeModel

Anything that "belongs" to a user, should either have a ForeignKey or ManyToManyField (depending on whether the object is owned by one user or many) to User on it. Then you can either filter the model based on the User:

SomeModel.objects.filter(user=some_user)
# where `user` is the name of your foreign key field

Or you can access the model through the user via reverse relations, for example:

class SomeModel(models.Model):
    ...
    user = models.ForeignKey(User)

# Later ...

some_user.somemodel_set.all()

The second method is more typical since you generally have the user already from the request, so in your view, you'd just do:

somemodels = request.user.somemodel_set.all()

To get all the SomeModels that belong to the currently logged-in user.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文