programing/python

[Django] It is impossible to add the field 'created_at' with 'auto_now_add=True'

쪽제비 2022. 5. 2. 10:38

It is impossible to add the field 'created_at' with 'auto_now_add=True' to description without providing a default. This is because the database needs something to populate existing rows.

 

------------

수정

선택 옵션창이 나오면 1, 1 을 선택

 

-------------

 

 

create_at 필드를 추가하고 makemigrations를 하자 나온 에러이다.

 

추가한 내용

class Description(models.Model):
    LOCALE_CHOICES = [
        ('KO_KR', 'KOREAN'),
        ('EN_US', 'ENGLISH/US'),
    ]
    locale = models.CharField(
        max_length=5,
        choices=LOCALE_CHOICES
    )

    detail = models.TextField()
    rough = models.TextField()

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

 

 

에러 내용으로는 auto_now_add 를 True로 한 경우 default 값이 필요하다는 것..

 

해결 방법은 매우 간단하다.

default를 설정해 주면 된다.

 

from django.utils import timezone

class Description(models.Model):
    LOCALE_CHOICES = [
        ('KO_KR', 'KOREAN'),
        ('EN_US', 'ENGLISH/US'),
    ]
    locale = models.CharField(
        max_length=5,
        choices=LOCALE_CHOICES
    )

    detail = models.TextField()
    rough = models.TextField()

    created_at = models.DateTimeField(auto_now_add=True, default=timezone.now())
    updated_at = models.DateTimeField(auto_now=True)