我正在关注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