Monday, 19 September 2016

// // 1 comment

Django: Difference between BLANK and NULL model attributes

At some point in my experience with django web framework, i have been puzzled as regards the meaning / difference between the above model attributes. Here is a pretty nice explanation for them:
NULL: setting the null attribute of a django model to True allows that particular field to save empty values as null in your database. null is a database terminology that represents a missing value. It is very different from a zero or a space value, it is just the database word for empty.(consult an SQL textbook for more explanation). The null attribute works on the database level and has nothing to do with form validation.The default value is False.
BLANK: django uses your model classes to perform  different abstractions which include automatically creating forms to feed data to your database where needed. setting blank = true allows any of these forms to be left blank. setting it to False makes it a required field hence raises an error on the form when left blank.
As the official docs has it:
Note that this is different than null. null is purely database-related, whereas blank is validation-related. 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.
the default value is False.
So when and how do i use blank=True or Null=True?
use blank=True when you want a user to continue his/her action without filling a form, vice versa.
use null=False when you don't want an a null value in your database irrespective how. However, Both attribute can be combined in some cases.
(blank=True, null=False) will raise an integrity error if the field is left blank.(TextField and CharField sends an empty string as value instead).
(blank=False, null=True) forbids the form from being empty but allows a null value in database if set manually through raw sql code or any other means.
I hope this helps.

1 comment:

  1. Thanks for sharing such amazing content which is very helpful for us. Please keep sharing like this. Also check to learn Django Python Framework Course or many more.

    ReplyDelete