Python

Python

By DeepSource

Field allows null but not blank PTC-W0906

Anti-pattern
Autofix

If null is True and blank is False then Django and the database disagree on whether empty values are allowed.

The null attribute specifies that the database will accept it if no value is passed to the field. The blank attribute specifies Django should not check if the value is present when Model.clean is called.

If Model.save is called via the shell without first calling Model.clean: the bad data will be saved and there may be unwanted side effects, such as:

  • Complex ORM queries
  • Validation error if the records are validated the next time
  • Inconsistent datatypes

These unwanted side effects can cause more serious problems that are hard to debug long after the original error occurred.

Not preferred:

class Feedback(models.Model):
    created = models.DateField(null=True)
    updated = models.DateField(null=True, blank=False)

Preferred:

class Feedback(models.Model):
    created = models.DateField(null=True, blank=True)
    updated = models.DateField(null=True, blank=True)