django의 Model attribute들은 아래와 같이 class attribute의 형태를 하고 있다.
models.py
from django.db import models
class Model(models.Model):
# These are class attributes, but specific to Django models
attribute1 = models.CharField(max_length=255)
attribute2 = models.TextField()
def __str__(self):
return f"{self.attribute1} - {self.attribute2}"
아래처럼 Model의 instance를 초기화할 때, kwargs 형태로 attribute1과 attribute2를 넘긴다.
new_instance = Model(attribute1=attribute1, attribute2=attribute2)
new_instance.save()
Model attribute는 class attribute로 정의되어 있는데, 초기화 과정에서 넘겨진 attribute1과 attribute2는 class attribute가 초기화된 것인가? 하는 질문이 순간 생겼다.
결론적으로 말하면 그렇지 않다.
Model에서 class 내에 직접 정의된 attribute1 및 attribute2와 같은 필드는 class attribute이다.
그러나 이는 해당 Model에 특수(specific)한 class attribute이며, 그 목적은 Model과 관련된 Database 테이블의 구조를 정의하는 것이다.
django의 Model class에서, class body 내부와 method 외부에서 직접 정의된 attribute들은 class attribute지만 다른 Python class들의 일반 class attribute들과는 다르다:
- Model attribute들은 Model의 database table의 필드들을 정의한다.
- 그러므로 django가 Model의 필들을 database column들에 매핑하기 위해 사용하는 descriptor로 기능한다.
반면에, instance attribute들은 Model을 instance화할 때 생성되며 각 instance마다 고유하다.
Instance 초기화를 위해 넘겨진 attribute1과 attribute2는 instance attribute의 값이며, 해당 특정 instance를 위해 세팅된다.
Instance attribute는 Model의 각 instance마다 다르며, class attribute와도 다르다.
즉 new_instance.attribute1와 new_instance.attribute2는 Model.attribute1와 Model.attribute2에 영향을 주지 않는다.
'Django' 카테고리의 다른 글
[Django] View 클래스의 as_view() 메서드 (0) | 2025.01.20 |
---|---|
[Django] 정적 파일(Static Files) 관리 (0) | 2025.01.17 |
[Django] urlpatterns의 작동 원리 (0) | 2024.12.29 |
[Django] reverse 함수 (0) | 2024.12.28 |
[django] CSRF verification error와 CSRF token 사용방법 (0) | 2023.11.22 |