From 529beb3d58b4ba18aa72dcd0fb3ec8dcf813e483 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Fri, 26 Apr 2019 23:34:15 +1000 Subject: [PATCH] Abstract DRF serializer validation - Subclass InvenTree.InvenTreeModelSerializer - Ensures model data is checked too (after serializer checks are performed) --- InvenTree/InvenTree/serializers.py | 18 +++++++++++++++++- InvenTree/part/api.py | 2 +- InvenTree/part/serializers.py | 9 +++------ 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/InvenTree/InvenTree/serializers.py b/InvenTree/InvenTree/serializers.py index ef4dd080fa..4ab1fd694d 100644 --- a/InvenTree/InvenTree/serializers.py +++ b/InvenTree/InvenTree/serializers.py @@ -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 diff --git a/InvenTree/part/api.py b/InvenTree/part/api.py index 839c00c7f2..96606c643a 100644 --- a/InvenTree/part/api.py +++ b/InvenTree/part/api.py @@ -235,4 +235,4 @@ bom_api_urls = [ # Catch-all url(r'^.*$', BomList.as_view(), name='api-bom-list'), -] \ No newline at end of file +] diff --git a/InvenTree/part/serializers.py b/InvenTree/part/serializers.py index fbd9421806..68066645bd 100644 --- a/InvenTree/part/serializers.py +++ b/InvenTree/part/serializers.py @@ -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)