Override get_initial() rather than is_valid()

This commit is contained in:
Oliver 2021-06-26 21:14:10 +10:00
parent ddbf863617
commit b2aa38fefa

View File

@ -45,17 +45,15 @@ class InvenTreeModelSerializer(serializers.ModelSerializer):
but also ensures that the underlying model class data are checked on validation.
"""
def is_valid(self, raise_exception=False):
def get_initial(self):
"""
Override the 'is_valid' method of the underlying ModelSerializer class.
- This is so we can intercept the data before save() is called.
- If we are creating a *new* model, replace any "missing" fields with the default values
- Default values are those specified by the database model
Construct initial data for the serializer.
Use the 'default' values specified by the django model definition
"""
# This serializer is *not* associated with a model instance
# This means that we are trying to *create* a new model
initials = super().get_initial()
# Are we creating a new instance?
if self.instance is None:
ModelClass = self.Meta.model
@ -63,16 +61,10 @@ class InvenTreeModelSerializer(serializers.ModelSerializer):
for field_name, field in fields.fields.items():
# Check if the field has a default value
if field.has_default():
initials[field_name] = field.default
# Value not specified?
if field_name not in self.initial_data:
self.initial_data[field_name] = field.default
return super().is_valid(raise_exception=raise_exception)
return initials
def run_validation(self, data=empty):
""" Perform serializer validation.