Skip to content

Instantly share code, notes, and snippets.

@bebosudo
Last active September 22, 2018 13:43
Show Gist options
  • Save bebosudo/5e2069ab99062c03602c09fbfa41a5eb to your computer and use it in GitHub Desktop.
Save bebosudo/5e2069ab99062c03602c09fbfa41a5eb to your computer and use it in GitHub Desktop.

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
                    field.default != NOT_PROVIDED):
                setattr(self, field.name, field.default)
        super().save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment