【问题标题】:Django RuntimeWarning: DateTimeField received a naive datetimeDjango RuntimeWarning:DateTimeField 收到一个天真的日期时间
【发布时间】:2020-01-19 14:47:44
【问题描述】:

我正在对接我的 Django 应用程序。由于我将数据库从 SQLite 更改为 Postgres,因此迁移失败并出现此错误:

RuntimeWarning: DateTimeField Posts.created_at received a naive datetime (2020-01-19 14:26:30.893128) while time zone support is active.
  warnings.warn("DateTimeField %s received a naive datetime (%s)"
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.CannotCoerce: cannot cast type time without time zone to timestamp with time zone
LINE 1: ..." TYPE timestamp with time zone USING "created_at"::timestam...

我已经搜索了其他问题并尝试了此修复https://stackoverflow.com/a/20106079/7400518
我使用的是datetime.now(),然后我将其更改为timezone.now(),但我仍然遇到同样的错误。 这是来自models.py的相关行

from django.utils import timezone

class Posts(models.Model):
    created_at = models.DateTimeField(default=timezone.now(), blank=True)

【问题讨论】:

  • 删除仍使用旧datetime 的迁移文件。此外,您应该使用auto_now_add

标签: python django postgresql docker


【解决方案1】:

我使用的是datetime.now(),然后我将其更改为timezone.now(),但我仍然遇到同样的错误。

更改模型不会更改迁移文件。您应该查找哪些迁移文件包含 datetime.now(),并删除它(连同所有其他依赖于它的迁移)。

此外,使用default=timezone.now() 不是一个好主意。它将使用您启动网络服务器的默认时间。这意味着如果服务器运行两天,时间戳仍将使用两天前的时间戳。

DateTimeField 有一个 auto_now_add=… [Django-doc] 在您添加对象时自动使用时间戳:

class Post(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)

这会将字段设置为blank=True,以及editable=False

【讨论】:

    猜你喜欢
    • 2013-09-08
    • 2018-02-15
    • 2016-08-19
    • 2014-03-28
    • 2019-08-06
    • 2021-02-17
    • 2014-01-29
    • 1970-01-01
    相关资源
    最近更新 更多