From b2aa38fefa66922165071690058686cfef7bee93 Mon Sep 17 00:00:00 2001 From: Oliver Date: Sat, 26 Jun 2021 21:14:10 +1000 Subject: [PATCH] Override get_initial() rather than is_valid() --- InvenTree/InvenTree/serializers.py | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/InvenTree/InvenTree/serializers.py b/InvenTree/InvenTree/serializers.py index f19ef23c00..82584bdbb0 100644 --- a/InvenTree/InvenTree/serializers.py +++ b/InvenTree/InvenTree/serializers.py @@ -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.