Abstract DRF serializer validation

- Subclass InvenTree.InvenTreeModelSerializer
- Ensures model data is checked too (after serializer checks are performed)
This commit is contained in:
Oliver Walters 2019-04-26 23:34:15 +10:00
parent e57a8cdcd1
commit 529beb3d58
3 changed files with 21 additions and 8 deletions

View File

@ -2,7 +2,6 @@
from __future__ import unicode_literals
from rest_framework import serializers
from rest_framework import generics
from django.contrib.auth.models import User
@ -22,3 +21,20 @@ class UserSerializerBrief(serializers.ModelSerializer):
'pk',
'username',
]
class InvenTreeModelSerializer(serializers.ModelSerializer):
"""
Inherits the standard Django ModelSerializer class,
but also ensures that the underlying model class data are checked on validation.
"""
def validate(self, data):
# Run any native validation checks first (may throw an ValidationError)
data = super(serializers.ModelSerializer, self).validate(data)
# Now ensure the underlying model is correct
instance = self.Meta.model(**data)
instance.clean()
return data

View File

@ -3,6 +3,8 @@ from rest_framework import serializers
from .models import Part, PartCategory, BomItem
from .models import SupplierPart, SupplierPriceBreak
from InvenTree.serializers import InvenTreeModelSerializer
class CategorySerializer(serializers.ModelSerializer):
@ -65,15 +67,10 @@ class PartSerializer(serializers.ModelSerializer):
]
class BomItemSerializer(serializers.ModelSerializer):
class BomItemSerializer(InvenTreeModelSerializer):
# url = serializers.CharField(source='get_absolute_url', read_only=True)
def validate(self, data):
instance = BomItem(**data)
instance.clean()
return data
part_detail = PartBriefSerializer(source='part', many=False, read_only=True)
sub_part_detail = PartBriefSerializer(source='sub_part', many=False, read_only=True)