djangodjango-modelsdjango-migrations

Django DateTimeField with auto_now_add asks for default


I have this field in my model created_at = models.DateTimeField( auto_now_add = True )

When I try to make migrations I get an error:

You are trying to add the field 'created_at' with 'auto_now_add=True' to user wi
thout a default; the database needs something to populate existing rows.

 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py

I tried to set the default value but it says default and auto_now_add are mutually exclusive. Of course I could just use default without auto_now_add but I want to know why this error pops up. Did I miss something?


Solution

  • You have already some rows without created_at value. But when you added following field and run migration

    created_at = models.DateTimeField( auto_now_add = True)
    

    It expects the existing row has created_at value. So, It warns you at the time of migrations.

    To solve this problem, you can choose the 1st option which says:
    Provide a one-off default now (will be set on all existing rows).

    By choosing the 1st option you are asking for value with default to timezone.now

    Select an option: 1
    Please enter the default value as valid Python.
    Accept the default 'timezone.now' by pressing 'Enter' or provide another value.
    The datetime and django.utils.timezone modules are available, so it is possible to provide e.g. timezone.now as a value.
    Type 'exit' to exit this prompt
    [default: timezone.now] >>> 
    

    Press Enter and it will populate existing rows with the current timestamp.