[Fixed]-Django null and empty string

7πŸ‘

βœ…

It is good practice. If strings were allowed to be null, there would be two ways to have an empty string: null and "". This gives you multiple values to check against, which is inefficient and messy.

This is a Django convention, but is good practice in all applications, unless you have the need for null to mean something different than "".

πŸ‘€Dave

3πŸ‘

It depends on the field.empty_strings_allowed attribute.

Some fields have it overridden to False. But CharField keeps it True, thus making Field._get_default return empty string as default β€” even if blank=True. The only way to get None as default is to have null=True on a field.

So if you have field in db that should never be null and not allow blanks to be never ever put in there by for e.g. objects.create. You need to put self.full_clean() β€” or other validation β€” in the model save method.

2πŸ‘

I think the string should be NULL too, but depends on your application see MySQL, better to insert NULL or empty string?.

If you want to store NULLs for an empty field, add null=True to the Field in question. See https://docs.djangoproject.com/en/dev/ref/models/fields/#null

πŸ‘€six8

Leave a comment