【问题标题】:DateField always return None valueDateField 总是返回 None 值
【发布时间】: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 关键字。不要假设它总是第一个参数。
  • &gt;&gt;&gt; s.pub_date = datetime.now() 之后添加 print s.pub_date 并显示输出

标签: python django


【解决方案1】:

您可能想设置auto_now_add parameter

pub_date = models.DateField(auto_now_add=True)

或者,您可以覆盖 .save() 方法:

class News(models.Model):
    title = models.CharField(max_length=70)
    full_text = models.TextField()
    pub_date = models.DateField()

    def save(self, *args, **kwargs):
        if not self.id:
            self.pub_date = datetime.datetime.today()
        super(News, self).save(*args, **kwargs)

【讨论】:

  • auto_now_add 可能更合适?
  • 是的,我的错,应该是auto_now_add
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-14
  • 2015-12-21
  • 2018-03-14
相关资源
最近更新 更多