【发布时间】:2018-09-28 17:57:58
【问题描述】:
class News(models.Model):
title = models.CharField(max_length=70)
full_text = models.TextField()
pub_date = models.DateField('-pub_date')
然后我跑 python manage.py 外壳 我为 News.pub_date 所做的任何价值都是无
我正在使用 sqlite3,当我打开数据库时,我可以看到日期值在那里。但是当我恢复一个对象时,pub_date 是无。之后我没有收到任何错误 s=News.objects.all()[0].pub_date 在此输入代码
>>> from face.models import News
>>> from datetime import datetime
>>> s=News()
>>> s.pub_date
>>> s=News()
>>> s.title="hgello"
>>> s.full_text="hello there"
>>> s.pub_date = datetime.now()
>>> s.show=True
>>> s.save()
>>> t=News.objects.all()
>>> t
[<News: This is title>, <News: second text>, <News: sample>, <News: hgello>]
>>> t=t[3]
>>> print t.pub_date
None
*我已经解决了这个问题。我刚刚删除了 sqllite3 的数据库文件。我认为它的发生是因为最初它被命名为 DateTimeField,然后我将其更改为 DateField。但是我在更改之间做了syncdb。因此 django 能够成功存储日期数据但无法恢复。并且 re-syncdb 并没有帮助我做了好几次。只有数据库的物理删除和数据库的重建结构解决了使用问题。 *
【问题讨论】:
-
您似乎混淆了查询和指定模型。您想通过
'-pub_date'实现什么目标? -
参数中的
-pub_date是什么? -
你可以忽略这个 -pub_date 它假设是数据库中的列名作为 DateField 对象的参数
-
然后使用
db_column关键字。不要假设它总是第一个参数。 -
在
>>> s.pub_date = datetime.now()之后添加 print s.pub_date 并显示输出