使用Django认证用户模型作为外键和反向关系 [英] Using Django auth User model as a Foreignkey and reverse relations

查看:489
本文介绍了使用Django认证用户模型作为外键和反向关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 django.contrib.auth.models 中使用用户模型。我有另一个模型叫做 Post ,它通过外键引用 User

I am using the User model from django.contrib.auth.models. I have another model called Post which references User through a foreign key.

问题是当我尝试通过

request.user.post_set.order_by('-timestamp')

我收到错误, 用户对象没有属性 post_set 。那么如何使用外键的默认认证模型?

I get an error, User object has no attribute post_set. So how do I use the default auth model with foreign keys?

推荐答案

您是否将包含Post模型的应用程序包含在您的设置中.py安装的应用程序?

Have you included the application containing the Post model in your settings.py installed apps?

例如

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'testapp'
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

并运行manage.py syncdb?

and ran manage.py syncdb?

python manage.py syncdb

ie Post模型的数据库表是否确实存在?

i.e does the database table for the Post model definately exist?

我做了一个快速测试发现没有问题:

I did a quick test and found no problems:

from django.db import models
from django.contrib.auth.models import User

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

(test) C:\Users\Steven\django_projects\test\testproj>python manage.py shell
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> test = User.objects.get(username='test')
>>> test.postmodel_set.all()
[]

这篇关于使用Django认证用户模型作为外键和反向关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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