Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django null and empty string

I find that when I insert nothing of a string form field through a form it captures it as an empty string ''.

However when I insert nothing of an integer form field through a form it captures it as [null].

Is this good practice? Should the string be null as well in the db?

like image 941
zentenk Avatar asked Sep 27 '11 06:09

zentenk


People also ask

What is difference between null and blank in Django?

null is purely database-related, whereas blank is validation-related(required in form). If null=True , Django will store empty values as NULL in the database . If a field has blank=True , form validation will allow entry of an empty value . If a field has blank=False, the field will be required.

How do I allow null values in Django model?

null=True will make the field accept NULL values. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the database.

Why we use null true in Django?

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 .

How do I check if a field is blank in Django?

If your foreign key field can take null values, it will return None on null, so to check if it was "left blank", you could simply check if the field is None .


1 Answers

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.

like image 147
Janusz Skonieczny Avatar answered Oct 14 '22 06:10

Janusz Skonieczny