我正在關注Django官方教程編寫你的第一個Django應用程序,第1部分。最後對在那裏,我必須給下面的命令:按照Django官方文檔說明的問題
q.was_published_recently()
和輸出應該是:
True
相反,我有:
False
這裏是我的models.py文件:
import datetime
from django.db import models
from django.utils import timezone
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return u'%s' % (self.question_text)
def was_published_recently(self):
return self.pub_date >= timezone.now()-datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
我猜測可能b我在timedelta函數有問題。但我不確定。
N.B:文件的具體步驟是:
>>> from polls.models import Question, Choice
>>> Question.objects.all()
[<Question: What's up?>]
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<Question: What's up?>]
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>
>>> Question.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Question matching query does not exist.
>>> Question.objects.get(pk=1)
<Question: What's up?>
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True
對我來說,timedelta看起來很好..隨着timedelta你從現在開始減去一天。我想問題是''''self.pub_date'''比一天更老,這就是爲什麼它正確輸出'''False'''。請在控制檯上輸入'''q.pub_date''',看看有什麼價值。 – chsymann 2014-12-02 16:22:57
好吧,「q.pub_date」命令正常工作:「datetime.datetime(2014,11,29,15,40,19,tzinfo =)」這意味着,它指的是從今天起兩天前。這是個問題嗎? –
ni8mr
2014-12-02 16:24:53