40
Django, Null=True or Blank=True or both
When we add a database field to Django, we have several options for defining the modal field. They usually have default values that we can override according to our needs.
In order to use modal fields effectively, one must have a thorough understanding of their definitions.
Every column in database is defined to hold certain attributes. Sometimes we want to keep our columns optional, thus hold NULL value, and we set these permissions as
NewField = models.charField( max_length=10, null=True)
# This sets the NewField to be optional field in DB
NewField = models.charField( max_length=10, null=False)
# This sets the NewField to be mandatory field in DB
Every Django model fields are also defined to hold certain attributes. Sometimes we want to keep our fields blank with no form value, and we set these permissions as:
NewField = models.charField( max_length=10, blank=True)
# This sets the NewField to be allowed to stay blank
NewField = models.charField( max_length=10, blank=False)
# This sets the NewField to not allowed to stay blank
Till now, it should be already clear that Null affects the database table definition and blank affects model validation. There are four ways to use these attributes:
# 1. Requires both
Name = models.charField( max_length=10, null=False, blank=False)
# 2. Requires DB value
Name = models.charField( max_length=10, null=False, blank=True)
# 3. Requires modal value
Name = models.charField( max_length=10, null=True, blank=False)
# 4. Requires none
Name = models.charField( max_length=10, null=True, blank=True)
Let's discuss each distinctively:
1.) Null=False, Blank=False
This is the default condition for modal fields. It means the value is required both in DB and in models.
2.) Null=False, Blank=True
This is a condition where forms don't require a value, but the field does.
Let's take an example: If your model has a field whose value is getting calculated from other models of the field. Then you would want to keep 'Black=True' to not accept values from the user, and 'Null=False' to enforce value is always provided.
3.) Null=True, Black=False
This is a condition where form requires a value, but DB doesn't. This is not a very commonly used configuration, I haven't seen one yet. (If you happen to know any, put them down in the comments.)
4.) Null=True, Black=True
This is a condition, where form doesn't require a value, and DB doesn't require a value as well. This is pretty self explanatory since the former is reflecting with later.
You might now have a good idea about what these two attributes mean, and how they are to be used together.
You can read more about them here
Have a good day. Happy Coding.
40