When declaring a model, there are many questions about null
vs blank
arguemnts (and this question is NOT about that)!
But what is the difference between if I mark a django.db.models.CharField
with default=""
vs blank=True
?
To me it seems like the same concept?
CodePudding user response:
Blank and Default arguments are not interchangeable. The resulting interaction will be different, depending on what combination you use. For example,
some_field = models.CharField(default='', max_length=20)
...will not allow you to save the model instance without entering data into some_field. The default empty string in this case is just allowing you to add that field to the model upon migration, since you aren't also allowing null with null=True.
some_field = models.CharField(blank=True, default='', max_length=20)
...will save without data, since blank=True.
Another way of putting this is that your default='' is allowing the non-nullable field to exist, and blank=True is allowing your non-nullable field to save() without data entry. If you try to migrate the following:
some_field = models.CharField(max_length=20)
...you'll get the following error:
You are trying to add a non-nullable field 'some_string' to YourModelName without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
...since a non-nullable field without a default can't exist on the database, but a blank=True field can. Note, I'm speaking here of PostgeSQL. This may or may not apply to any/every other DB out there.
CodePudding user response:
Field.null If True, Django will store empty values as NULL in the database. default is False. Avoid using null in CharField or TextField
Field.blank if True, the field is allowed to be blank. Default is False.
NOTE: This is different than null. null is purely database related, where blank is validation-related.