Django用户表的外键 [英] Foreign key to User table in django

查看:57
本文介绍了Django用户表的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django的内置contrib.auth模块,并为添加帖子"时设置了与用户的外键关系:

I'm using django's built-in contrib.auth module and have setup a foreign key relationship to a User for when a 'post' is added:

class Post(models.Model):
    owner = models.ForeignKey('User')
    # ... etc.

现在,当涉及到实际添加帖子时,我不确定在调用save()之前在所有者字段中提供什么内容.我期望用户会话中有类似id的内容,但我注意到User没有user_id或id属性.我应该从用户的身份验证会话中提取什么数据来填充所有者字段?我试图查看数据库表中正在发生的事情,但是在sqlite设置中还不太清楚.

Now when it comes to actually adding the Post, I'm not sure what to supply in the owner field before calling save(). I expected something like an id in user's session but I noticed User does not have a user_id or id attribute. What data is it that I should be pulling from the user's authenticated session to populate the owner field with? I've tried to see what's going on in the database table but not too clued up on the sqlite setup yet.

感谢您的帮助...

推荐答案

您要提供用户"对象.IE.您可以从User.objects.get(pk = 13)获得相同的结果.

You want to provide a "User" object. I.e. the same kind of thing you'd get from User.objects.get(pk=13).

如果您使用的是Django的身份验证组件,则该用户还将附加到请求对象,您可以直接在您的视图代码中使用它:

If you're using the authentication components of Django, the user is also attached to the request object, and you can use it directly from within your view code:

request.user

如果用户未通过身份验证,则Django将返回django.contrib.auth.models.AnonymousUser的实例.(每个 http://docs.djangoproject.com/en/dev/ref/request-response/#attributes )

If the user isn't authenticated, then Django will return an instance of django.contrib.auth.models.AnonymousUser. (per http://docs.djangoproject.com/en/dev/ref/request-response/#attributes)

这篇关于Django用户表的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆