본문 바로가기

Development/Django

[django] Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField' 경고?

경고 내용을 읽어보면 각 모델에서 primary key 타입을 명시하지 않아서 생긴 경고입니다.

하지만 장고에선 자동으로 primary key로 사용할 타입을 자동으로 설정해준다고 합니다.

 

By default, Django gives each model an auto-incrementing primary key with the type specified per app in AppConfig.default_auto_field or globally in the DEFAULT_AUTO_FIELD setting.

For example:

id = models.BigAutoField(primary_key=True)

위 코드는 모델에서 사용할 primary key를 BigAutoField(1부터 시작하는 64bit의 정수)로 설정합니다.

django는 자동으로 증가하는 필드로 id 라는 column 이름의 primary key를 생성해주며, 이 때 기본 필드는 

다음과 같이 DEFAULT_AUTO_FIELD을 설정하여 직접 기본 primary key 타입을 정해줄 수 있습니다.

 

settings.py

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

(따로 설정해주지 않으면 BigAutoField로 설정되는 것 같습니다.)

 

하지만, django 4.2 버전에선 DEFAULT_AUTO_FIELD 설정을 바꾸고 Migration을 생성할 경우,

auto-created 된 테이블 즉 Many to Many(다대다) 관계에 있는 두 모델 사이엔 연결 테이블이 생성이 되는데

이 연결 테이블의 primary key는 migration이 적용되지 않는다고 합니다.

즉 이 때 수동으로 기본 키를 바꿔주어야 한다는 것인데...

역시 db 설계는 정말 중요한 것 같습니다.

Unfortunately, the primary keys of existing auto-created through tables cannot currently be updated by the migrations framework. This means that if you switch the value of DEFAULT_AUTO_FIELD and then generate migrations, the primary keys of the related models will be updated, as will the foreign keys from the through table, but the primary key of the auto-created through table will not be migrated.

 id 타입은 int, long, uuid 등 여러가지가 될 수있습니다.

아래는 django에서 각 타입 별 사용할 수 있는 필드들입니다.

AutoField 정수 타입, -2^32 ~ +2^32 - 1
BigAutoField 64비트 정수, 1 ~ 2^64-1
BigIntegerField 64비트 정수, -2^64 ~ +2^64-1
BooleanField true/false 필드
CharField string 필드, 더 큰 크기의 string일 경우 TextField 사용
DateField 파이썬에서 datetime.datetime 표현되는 필드
EmailField EmailValidator를 사용하는 CharField

데이터베이스의 무결성 (정확성, 일관성, 유효성)을 지키기 위해서 여러 옵션을 사용하는 것이 좋으며

CharField 같은 경우엔 unique=true를 넣어주는 등의 처리가 필요합니다.

 

필드와 사용 가능한 옵션에 대해 더 자세한 내용은 아래에서 확인하실 수 있습니다.

https://docs.djangoproject.com/en/4.2/ref/models/fields/

 

Django

The web framework for perfectionists with deadlines.

docs.djangoproject.com

처음에 언급했던

경고 메세지를 없애려면 model 클래스에서 id로 사용할 model.필드 타입을 명시하고, (primary_key=True)로 설정하면 됩니다.

class Question(models.Model):
    id = models.BigAutoField(primary_key=True)
    author = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="author_question"
    )
    subject = models.CharField(max_length=200)
    content = models.TextField()
    create_date = models.DateTimeField()
    modify_date = models.DateTimeField(null=True, blank=True)
    voter = models.ManyToManyField(User, related_name="voter_question")

    def __str__(self):
        return self.subject

 

참고 자료

https://docs.djangoproject.com/en/4.2/topics/db/models/#automatic-primary-key-fields

 

Django

The web framework for perfectionists with deadlines.

docs.djangoproject.com

 

 

'Development > Django' 카테고리의 다른 글

[django] class-based view와 function-based view?  (0) 2023.05.29