【发布时间】:2019-01-05 21:53:23
【问题描述】:
如何在给定日期和时间的情况下手动设置 DateTimeField 值?
这是我的模型,我正在尝试将日期和时间值分配给“created_at”字段:
class Attendance(models.Model):
employee = models.ForeignKey(Employee)
company = models.ForeignKey(Company)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.employee.username
这是我在控制台中尝试过的:
> o = Attendance.objects.last()
> o.updated_at
datetime.datetime(2018, 6, 26, 0, 45, 31, 829827, tzinfo=<UTC>)
> x = datetime.strptime('17/07/2018 12:20', '%d/%m/%Y %H:%M')
> x
datetime.datetime(2018, 7, 17, 12, 20)
>o.updated_at = x
o.save()
>z = Attendance.objects.last()
>z.updated_at
datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, tzinfo=<UTC>)
请注意,我设置了“2018,7,17”,但它显示为“2018,7,29”。作业正确吗?可能它也需要时区。
【问题讨论】:
-
你确定o和z是同一个对象吗?此代码似乎正确,但可能是更改/保存对象会使不同的对象响应“Attendance.objects.last()”。
-
是的,在我的本地机器上开发中是一样的。有人告诉我 auto_now_add 可能是个问题,应该改用默认值
-
您意识到您的 auto_now 可能正在工作并覆盖您的 updated_at 字段,对吗?由于您正在更新 updated_at 字段并获得今天的结果,因此根据应用 auto_now 的时间,您似乎获得了两个可能正确的结果之一。
-
哦,没意识到,因为我不想接触 created_at,所以正在测试 updated_at
-
也许你可以添加一个额外的字段来检查 updated_at ..... 对我来说,你的代码看起来像写的那样工作。
标签: python django datetime django-queryset