【问题标题】:Django ORM update field to NOW() returning 0 errorDjango ORM 更新字段到 NOW() 返回 0 错误
【发布时间】:2021-05-12 23:39:51
【问题描述】:

我正在尝试遍历结果列表,处理它们,然后更新它们的“updated_details”字段。

users_to_update = TiktokUser.objects.filter(Q(updated_details__lt=datetime.utcnow() - timedelta(weeks=1)) | Q(updated_details__isnull=True))[0:1]
    for user_to_update in users_to_update:
        print(datetime.now())
        user_to_update.updated_details = datetime.now()
        user_to_update.save()

我的想法是在每个循环中,我将updated_details 设置为当前时间戳。我的print() 语句在这里正确打印出当前日期和时间,但是当我更新记录本身并保存时,出现以下错误:

['“0000-00-00 00:00:00.000000” value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) but it is an invalid date/time.']

这对我来说意味着它正在尝试将其设置为 0。

我的模型定义是:

class User(models.Model):
    ...
    updated_details = models.DateTimeField(blank=True, null=True)
    ...

如何让 Django 将字段设置为当前的DateTime

【问题讨论】:

  • 你在settings.py中设置过日期时间格式吗??

标签: django


【解决方案1】:

您正在使用 python 日期时间,请使用 django 日期时间,它基于您的 django 项目的设置文件

from django.utils.timezone import now
users_to_update = TiktokUser.objects.filter(Q(updated_details__lt=datetime.utcnow() - timedelta(weeks=1)) | Q(updated_details__isnull=True))[0:1]
for user_to_update in users_to_update:
        user_to_update.updated_details = now()
        user_to_update.save()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多