2

I decided to add a created = Models.DateTimeField(auto_now_add = True) field to a model which already has objects instantiated (without created field of course), and I saved them as initial_data

So now when I run syncdb, I get the error app_model.created may not be NULL since it's trying to load objects without that field.

So how do I fix this? I wish it automatically assigned the time when I call syncdb as object.created. Can I make that?

Thanks for any help!

jeff
  • 13,055
  • 29
  • 78
  • 136

2 Answers2

1

I'd use a default value instead of auto_now_add.

from django.utils.timezone import now

class Something(models.Model):
    created = models.DateTimeField(default=now, editable=False)

It also makes your data field timezone aware and uses UTC.

C14L
  • 12,153
  • 4
  • 39
  • 52
0

After you add a new field to a model, you need to create and run migrations, by running:

>>> python manage.py makemigrations
>>> python manage.py migrate

In this case, when it try to create the new non-null field, it will ask you if you want to add create a default value in your model or if you want to define a value now, you can choose add a value right there in console. When prompt ask for the value, you can use datetime module, so you can write as value:

datetime.datetime.now()
Gocht
  • 9,924
  • 3
  • 42
  • 81