数据如何连接到特定的用户 ID?
我是 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“属于”用户的任何内容都应该具有
ForeignKey
或ManyToManyField
(取决于该对象是由一个用户还是多个用户拥有)到User< /代码> 就可以了。然后,您可以根据
用户
过滤模型:或者您可以通过反向关系通过用户访问模型,例如:
第二种方法更为典型,因为您通常已经从请求中获得了用户,因此在您看来,您只需执行以下操作:
获取属于当前登录用户的所有
SomeModel
。Anything that "belongs" to a user, should either have a
ForeignKey
orManyToManyField
(depending on whether the object is owned by one user or many) toUser
on it. Then you can either filter the model based on theUser
:Or you can access the model through the user via reverse relations, for example:
The second method is more typical since you generally have the user already from the request, so in your view, you'd just do:
To get all the
SomeModel
s that belong to the currently logged-in user.