mirror of
https://github.com/inventree/InvenTree
synced 2024-08-30 18:33:04 +00:00
Override get_initial() rather than is_valid()
This commit is contained in:
parent
ddbf863617
commit
b2aa38fefa
@ -45,17 +45,15 @@ class InvenTreeModelSerializer(serializers.ModelSerializer):
|
|||||||
but also ensures that the underlying model class data are checked on validation.
|
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.
|
Construct initial data for the serializer.
|
||||||
|
Use the 'default' values specified by the django model definition
|
||||||
- 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
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# This serializer is *not* associated with a model instance
|
initials = super().get_initial()
|
||||||
# This means that we are trying to *create* a new model
|
|
||||||
|
# Are we creating a new instance?
|
||||||
if self.instance is None:
|
if self.instance is None:
|
||||||
ModelClass = self.Meta.model
|
ModelClass = self.Meta.model
|
||||||
|
|
||||||
@ -63,16 +61,10 @@ class InvenTreeModelSerializer(serializers.ModelSerializer):
|
|||||||
|
|
||||||
for field_name, field in fields.fields.items():
|
for field_name, field in fields.fields.items():
|
||||||
|
|
||||||
# Check if the field has a default value
|
|
||||||
if field.has_default():
|
if field.has_default():
|
||||||
|
initials[field_name] = field.default
|
||||||
|
|
||||||
# Value not specified?
|
return initials
|
||||||
if field_name not in self.initial_data:
|
|
||||||
|
|
||||||
self.initial_data[field_name] = field.default
|
|
||||||
|
|
||||||
|
|
||||||
return super().is_valid(raise_exception=raise_exception)
|
|
||||||
|
|
||||||
def run_validation(self, data=empty):
|
def run_validation(self, data=empty):
|
||||||
""" Perform serializer validation.
|
""" Perform serializer validation.
|
||||||
|
Loading…
Reference in New Issue
Block a user