If we have a model with some fields that have default
values (e.g. a cost = DecimalField(default=0, null=false)
), and we receive a form with that field set as None
, django will complain with a NOT NULL constraint failed
.
We can manually set the fields of interest in the save()
method of the models, or simply add this class to all the django Models, which will automatically discover and set the null fields having a default value.
from django.db.models.fields import NOT_PROVIDED
class SetModelDefaultsOnSave:
def save(self):
for field in self._meta.get_fields():
if (not field.auto_created and getattr(self, field.name) is None and