In Django models.py, what's the difference between default, null, and blank?

前端 未结 5 1246
-上瘾入骨i
-上瘾入骨i 2020-12-04 12:45
  • null=True
  • blank=True
  • default = 0

What\'s the difference? When do you use what?

5条回答
  •  死守一世寂寞
    2020-12-04 13:30

    Null: It is database-related. Defines if a given database column will accept null values or not.

    Blank: It is validation-related. It will be used during forms validation, when calling form.is_valid().

    Default: All Time it store the given value(default value) to the field if one doesn't provide any value for this field.

    The default values of null and blank are False.

    That being said, it is perfectly fine to have a field with null=True and blank=False. Meaning on the database level the field can be NULL, but in the application level it is a required field.

    Now, where most developers get it wrong: Defining null=True for string-based fields such as CharField and TextField. Avoid doing that. Otherwise, you will end up having two possible values for “no data”, that is: None and an empty string. Having two possible values for “no data” is redundant. The Django convention is to use the empty string, not NULL.

提交回复
热议问题