#Optional model fields
10 messages · Page 1 of 1 (latest)
blank=True is only for CharFields, causing them to store an empty string instead of NULL; you should use null=True for all optional fields
okay thanks!
Basically:
null=Trueallows the database to store NULL in that fieldblank=Truetells Django to actually store a blank string instead of a NULL for aCharField, so you don't end up with two possible options for an "empty" value in the database
can I use null instead of blank for Charfield to make my queries simpler? I wouldn't have to make separate conditions to check for null and blank
That was the intention of blank=True, to force everything for that field to be "" instead of NULL, so your queries are simpler. But that actually only applies to the Django Admin, so it's still possible to create objects with NULL outside of that. There's some info here about it with regards to string-based fields specifically: https://docs.djangoproject.com/en/5.1/ref/models/fields/#null
Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.
Isnt blank more of a form thing? It doesnt actually let you save blank, it disables the form validation for being blank and allows the default blank value to be current value. For some fields, json field for example, having null false and blank true ends up with an error because the field doesnt have a default blank value
If you have a null true blank false field, admin doesnt allow you to save it empty because it doesn't pass the validation
Yes, it's a form thing