Django ORM更新字段NOW()返回0错误



我正在尝试循环通过结果列表,处理它们,然后更新它们的"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?

你正在使用python的datetime,请使用django的datetime它是基于你的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()

最新更新