When we add a model field in Django we generally write:
models.CharField(max_length=100, null=True, blank=True)
The same is done with ForeignKey, DecimalField etc. What is the basic difference between:
null=Trueonlyblank=Trueonlynull=Trueandblank=True
in respect to different (CharField, ForeignKey, ManyToManyField, DateTimeField) fields? What are the advantages/disadvantages of using option 1, 2, or 3?
null=TruesetsNULL(versusNOT NULL) on the column in your DB. Blank values for Django field types such asDateTimeFieldorForeignKeywill be stored asNULLin the DB.blankdetermines whether the field will be required in forms. This includes the admin and your custom forms. Ifblank=Truethen the field will not be required, whereas if it’sFalsethe field cannot be blank.The combo of the two is so frequent because typically if you’re going to allow a field to be blank in your form, you’re going to also need your database to allow
NULLvalues for that field. The exception isCharFields andTextFields, which in Django are never saved asNULL. Blank values are stored in the DB as an empty string ('').A few examples:
Obviously, Those two options don’t make logical sense to use (though there might be a use case for
null=True, blank=Falseif you want a field to always be required in forms, optional when dealing with an object through something like the shell.)CHARandTEXTtypes are never saved asNULLby Django, sonull=Trueis unnecessary. However, you can manually set one of these fields toNoneto force set it asNULL. If you have a scenario where that might be necessary, you should still includenull=True.