본문 바로가기

Django

Django 모델이 생성된 후에 default date 컬럼 추가하기

반응형
  1. 모델에 DateTimeField 추가
    1. create_at = models.DateTimeField(default=timezone.now())
  2. makemigrations를 이용하여 DB Schema 생성 준비
    1. 이 때 기존에 row가 있기 때문에 이를 어떤 값으로 채울지 결정하라고 한다.
    2. timezone.now를 입력하여 현재 시간으로 기존 로우에 대한 값을 설정한다.
    3. $ python manage.py makemigrations
      System check identified some issues:
      
      WARNINGS:
      HelloWorld.Post.create_at: (fields.W161) Fixed default value provided.
              HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
      You are trying to add a non-nullable field 'create_at' to comment without a default; we can't do that (the database needs something to populate existing rows).
      Please select a fix:
       1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
       2) Quit, and let me add a default in models.py
      Select an option: 1
      Please enter the default value now, as valid Python
      The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
      Type 'exit' to exit this prompt
      >>> timezone.now
      Migrations for 'HelloWorld':
        HelloWorld/migrations/0003_auto_20220210_1024.py
          - Add field create_at to comment
          - Add field create_at to post
          - Alter field post_contents on post
  3. DB에 반영한다.
    1. $ python manage.py migrate
      System check identified some issues:
      
      WARNINGS:
      HelloWorld.Post.create_at: (fields.W161) Fixed default value provided.
              HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
      Operations to perform:
        Apply all migrations: HelloWorld, admin, auth, contenttypes, sessions
      Running migrations:
        Applying HelloWorld.0003_auto_20220210_1024... OK

 

반응형