2019.08.23 장고 모델의 default, blank, null 에 관하여

django 모델을 설정할 때, default와 blank, null에 관해서

  • 먼저 장고 model을 설정 할 떄 필드의 옵션에 들어가는 default와 blank, null이 각각 무엇을 의미하는지 궁금해졌다.
  • 해당 내용에 대해서 찾아보았다.
The blank option is used in the form validation, and the null is used when writing to database.
So you might add null=True to that field.
EDIT: continue the comment
Considering the two steps when saving object:
1. Validator(controlled by blank)
2. Database limitation(controlled by null)

For default option, take IntegerField for example,


default=5, blank=True, null=False, pass (1) even if you didn't assign a value(having blank=True), pass (2) because it has a default value(5) and writes 5 instead of None to DB.


blank=True, null=False, which pass (1) but not (2), because it attempts to write None to DB.

Thus, if you want to make a field optional, use either default=SOMETHING, blank=True, null=False or blank=True, null=True.

장고 모델에서 저장이 될 때

  • 장고에서 해당 모델 object를 저장 할 때 2가지 과정을 거친다.
    • 첫 번째는 validator(controlled by blank) 즉 검증에서 가능한지 파악하고
    • 두 번째는 Database limitation(controlled by null) 데이터베이스에 넣을 때이다.

예를 들어서 설명해보자

  • 만약에 default=5, blank=True, null=False라고 하면
  • 값(blank=True)을 주지 않아도 통과하게 될 것이다. 왜냐하면 blank=True 때문에 validation을 넘어가게 되고 , default value가 5이기 때문에 db에는 None 대신에 5가 저장될 것이기 때문이다.
  • 하지만 만약에 default value가 없이, blank=True 그리고 null=False만 있다고 하면 통과 할 수 없다. validation은 통과하지만 null을 DB에 저장하려고 시도할 때 null=False이므로 저장할 수가 없다.

따라서 기본적인 옵션을 만들때는

  1. default= something , blank=True, null=False
  2. blank=True, null=True
  3. 위의 2가지 조건 중에 한개를 선택해주어야지만 저장이 될 수 있다.

'Django' 카테고리의 다른 글

Django queryset filter와 exists()  (0) 2019.12.28
Django Lock에 관해서  (0) 2019.12.28
Django admin message  (1) 2019.12.28
Django super & after save  (0) 2019.12.28
Django 트랜젝션  (0) 2019.12.28

+ Recent posts