gpt4 book ai didi

python - auto_now_add 字段覆盖我的输入

转载 作者:行者123 更新时间:2023-12-05 05:21:47 27 4
gpt4 key购买 nike

给定一个模型

class Foo(models.Model):
bar = models.DateTimeField(auto_now_add=True)

当我这样做

my_foo = Foo.objects.create(bar=yesterday)

那么 my_bar.foo 不是昨天而是现在。我必须做的

my_foo = Foo.objects.create()
my_foo.bar = yesterday
my_foo.save()

过去不是这样,但对于 Django 1.8.17 是这样

最佳答案

来自docs :

The auto_now and auto_now_add options will always use the date in the default timezone at the moment of creation or update. If you need something different, you may want to consider simply using your own callable default or overriding save() instead of using auto_now or auto_now_add; or using a DateTimeField instead of a DateField and deciding how to handle the conversion from datetime to date at display time.

所以你应该这样做

bar = models.DateTimeField(default=date.today)

关于python - auto_now_add 字段覆盖我的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42219821/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com