python - django:为什么我会收到这个错误:AttributeError: 'method_descriptor' object has no attribute 'today'?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4909577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python - django: why am I getting this error: AttributeError: 'method_descriptor' object has no attribute 'today'?
提问by leora
I have the following python code:
我有以下python代码:
from django.db import models
from datetime import datetime
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
In a python shell, I am trying to run:
在 python shell 中,我试图运行:
p = Poll.objects.get(pk=1)
p.was_published_today()
The first line works fine but the second line gives me this error:
第一行工作正常,但第二行给了我这个错误:
AttributeError: 'method_descriptor' object has no attribute 'today'
AttributeError: 'method_descriptor' 对象没有属性 'today'
采纳答案by Adam Vandenberg
You probably want "import datetime", not "from datetime import datetime".
您可能想要“导入日期时间”,而不是“从日期时间导入日期时间”。
"date" is a class on the datetime module, but it is also a method on the "datetime.datetime" class.
“date”是 datetime 模块上的一个类,但它也是“datetime.datetime”类上的一个方法。
回答by rootart
You need do like this one (ipython output)
你需要这样做(ipython 输出)
In [9]: datetime.today().date() Out[9]: datetime.date(2011, 2, 5)
So need to be
所以需要
def was_published_today(self):
return self.pub_date.date() == datetime.today().date()
回答by Joe
The top answer is correct, but if you don't want to import all of datetime you can write
最佳答案是正确的,但是如果您不想导入所有日期时间,则可以编写
from datetime import date
and then replace
然后更换
datetime.date.today()
with
和
date.today()

