From 3074dac68dfe9f16e7ae63035df0fccd54a0994b Mon Sep 17 00:00:00 2001
From: Samuel Gaist <samuel.gaist@idiap.ch>
Date: Wed, 22 Apr 2020 16:45:24 +0200
Subject: [PATCH] [common][serializers] Implement handling of return field
 selection in query parameters for PUT

---
 beat/web/common/serializers.py | 30 +++++++++++++++++++++++++++---
 1 file changed, 27 insertions(+), 3 deletions(-)

diff --git a/beat/web/common/serializers.py b/beat/web/common/serializers.py
index e451ce0d3..8ad155b06 100644
--- a/beat/web/common/serializers.py
+++ b/beat/web/common/serializers.py
@@ -26,6 +26,8 @@
 ###############################################################################
 
 import copy
+import simplejson as json
+import difflib
 
 from django.conf import settings
 
@@ -44,9 +46,6 @@ from .models import Shareable, Versionable, Contribution
 from .exceptions import ContributionCreationError
 from .fields import JSONSerializerField, StringListField
 
-import simplejson as json
-import difflib
-
 
 # ----------------------------------------------------------
 
@@ -333,6 +332,31 @@ class ContributionModSerializer(serializers.ModelSerializer):
 
         return super().update(instance, validated_data)
 
+    def filter_representation(self, representation):
+        """Filter out fields if given in query parameters"""
+
+        request = self.context["request"]
+        fields = request.query_params.get("fields", None)
+        if fields is not None:
+            fields = fields.split(",")
+            to_remove = [key for key in representation.keys() if key not in fields]
+            for key in to_remove:
+                representation.pop(key)
+
+            # Retrieve the description in HTML format
+            if "html_description" in fields:
+                description = self.instance.description
+                if len(description) > 0:
+                    representation["html_description"] = ensure_html(description)
+                else:
+                    representation["html_description"] = ""
+
+        return representation
+
+    def to_representation(self, instance):
+        representation = super().to_representation(instance)
+        return self.filter_representation(representation)
+
 
 # ----------------------------------------------------------
 
-- 
GitLab