djangodjango-modelsdjango-databasedjango-syncdb

Django creating a DateTimeField(auto_now_add) on a populated table


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!


Solution

  • 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.