Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto_now_add fields override my input

Given a model

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

When I do

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

Then my_bar.foo is not yesterday but now. I have to do

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

This didn't use to be the case, but is true for Django 1.8.17

like image 625
Eldamir Avatar asked Dec 07 '25 11:12

Eldamir


1 Answers

From the 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.

So you should do that instead

bar = models.DateTimeField(default=date.today)
like image 169
Sayse Avatar answered Dec 10 '25 01:12

Sayse