【发布时间】:2014-11-25 19:49:58
【问题描述】:
在https://docs.djangoproject.com/en/1.7/intro/tutorial01/ 上完成 Django 1.7 教程。对于给定的问题,我无法获得 choice_set.all()。
这里是 python manage.py shell 命令行:
Python 2.7.8 (default, Aug 24 2014, 21:26:19)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from elections.models import Question, Choice
>>> q = Question.objects.get(pk=1)
>>> # Display any choices from the related object set.
>>> q.choice_set.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Question' object has no attribute 'choice_set'
我的models.py 按照教程使用 ForeignKey 从选择到问题的关系:
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
def __unicode__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
def __unicode__(self):
return self.choice_text
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
我正在使用 sqlite3 数据库。为什么choice_set 没有属性?
【问题讨论】:
-
您的错误与您显示的代码不符。确保您清除所有 pyc 文件并重试
-
@karthikr 我一开始复制了错误的错误。正确的错误消息是:AttributeError: 'Question' object has no attribute 'choice_set'。我删除了所有 .pyc 文件并重新测试并收到相同的错误
-
数据库中是否有任何值,并且在任何模型更改后数据库是否是最新的?
-
你能试试 question = models.ForeignKey(Question, related_name="choices") 并通过 q.choices.all() 访问选择吗
-
我用你的模型创建了项目,一切正常。尝试重新安装环境并清理所有
*.pyc