0
使用Django 1.7教程https://docs.djangoproject.com/en/1.7/intro/tutorial01/。對於給定的問題,我無法獲得choice_set.all()
。Django教程1.7 ForeignKey
這裏是蟒蛇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 2014-10-01 03:02:48
@karthikr我首先複製了錯誤的錯誤。正確的錯誤消息是:AttributeError:'Question'對象沒有屬性'choice_set'。我刪除了所有的.pyc文件並重新測試並收到相同的錯誤 – tromboneamafone 2014-10-01 03:27:44
數據庫中是否有任何值,並且在任何模型更改後數據庫是最新的? – osowskit 2014-10-01 05:01:00