org.sonar.l10n.py.rules.python.S6553.html Maven / Gradle / Ivy
This rule suggests avoiding the use of "null=True" on string-based fields such as CharField and TextField in Django models. Instead, it recommends
using blank=True, which allows an empty string as a valid value while still maintaining the ability to query and filter on the field.
Why is this an issue?
Using "null=True" on string-based fields can lead to inconsistent and unexpected behavior. In Django, "null=True" allows the field to have a NULL
value in the database. However, the Django convention to represent the absence of data for a string is an empty string. Having two ways to represent
the absence of data can cause problems when querying and filtering on the field. For example, if a CharField with "null=True" has a value of NULL in
the database, querying for an empty string will not return that object.
How to fix it
Instead of using "null=True", use "blank=True" on string-based fields such as CharField and TextField. This allows an empty string as a valid value
while still maintaining the ability to query and filter on the field. If a field should not be left empty, specify a default value using the default
argument.
Code examples
Noncompliant code example
class ExampleModel(models.Model):
name = models.CharField(max_length=50, null=True)
Compliant solution
class ExampleModel(models.Model):
name = models.CharField(max_length=50, blank=True)
Exceptions
If unique=True
and blank=True
are both set, null=True
is required to avoid unique constraint violations when
saving multiple objects with blank values. No issue will be raised in this scenario.
Resources
Documentation