[RFC 04/11] REST: Introduce some helper code

Andy Doan andy.doan at linaro.org
Sat Apr 16 04:24:00 AEST 2016


DRF lends its self to a lot of repetitive code like:

 Serializer:
   Meta:
     model = Foo

 ViewSet:
    queryset = Foo.objects


This reduces the amount of boiler plate code needed for most of our
endpoints so that its easier to audit.

Signed-off-by: Andy Doan <andy.doan at linaro.org>
---
 patchwork/views/rest_api.py | 21 ++++++++++++++-------
 1 file changed, 14 insertions(+), 7 deletions(-)

diff --git a/patchwork/views/rest_api.py b/patchwork/views/rest_api.py
index a4f6886..f6385a3 100644
--- a/patchwork/views/rest_api.py
+++ b/patchwork/views/rest_api.py
@@ -48,16 +48,23 @@ class PatchworkPermission(permissions.BasePermission):
         return obj.is_editable(request.user)
 
 
-class ProjectSerializer(ModelSerializer):
-    class Meta:
-        model = Project
+class PatchworkViewSet(ModelViewSet):
+    pagination_class = PageSizePagination
+
+    def get_queryset(self):
+        return self.serializer_class.Meta.model.objects.all()
+
 
+def create_model_serializer(model_class):
+    class PatchworkSerializer(ModelSerializer):
+        class Meta:
+            model = model_class
+    return PatchworkSerializer
 
-class ProjectViewSet(ModelViewSet):
+
+class ProjectViewSet(PatchworkViewSet):
     permission_classes = (PatchworkPermission,)
-    queryset = Project.objects.all()
-    serializer_class = ProjectSerializer
-    pagination_class = PageSizePagination
+    serializer_class = create_model_serializer(Project)
 
 
 router = DefaultRouter()
-- 
2.7.4



More information about the Patchwork mailing list