diff --git a/src/documents/serialisers.py b/src/documents/serialisers.py index faded5125..69cbb4092 100644 --- a/src/documents/serialisers.py +++ b/src/documents/serialisers.py @@ -7,6 +7,28 @@ from .models import Correspondent, Tag, Document, Log, DocumentType from .parsers import is_mime_type_supported +# https://www.django-rest-framework.org/api-guide/serializers/#example +class DynamicFieldsModelSerializer(serializers.ModelSerializer): + """ + A ModelSerializer that takes an additional `fields` argument that + controls which fields should be displayed. + """ + + def __init__(self, *args, **kwargs): + # Don't pass the 'fields' arg up to the superclass + fields = kwargs.pop('fields', None) + + # Instantiate the superclass normally + super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) + + if fields is not None: + # Drop any fields that are not specified in the `fields` argument. + allowed = set(fields) + existing = set(self.fields) + for field_name in existing - allowed: + self.fields.pop(field_name) + + class CorrespondentSerializer(serializers.ModelSerializer): document_count = serializers.IntegerField(read_only=True) @@ -90,7 +112,7 @@ class DocumentTypeField(serializers.PrimaryKeyRelatedField): return DocumentType.objects.all() -class DocumentSerializer(serializers.ModelSerializer): +class DocumentSerializer(DynamicFieldsModelSerializer): correspondent = CorrespondentField(allow_null=True) tags = TagsField(many=True) diff --git a/src/documents/views.py b/src/documents/views.py index b1d93b77b..10cb30eb3 100755 --- a/src/documents/views.py +++ b/src/documents/views.py @@ -131,6 +131,17 @@ class DocumentViewSet(RetrieveModelMixin, "added", "archive_serial_number") + def get_serializer(self, *args, **kwargs): + fields_param = self.request.query_params.get('fields', None) + if fields_param: + fields = fields_param.split(",") + else: + fields = None + serializer_class = self.get_serializer_class() + kwargs.setdefault('context', self.get_serializer_context()) + kwargs.setdefault('fields', fields) + return serializer_class(*args, **kwargs) + def update(self, request, *args, **kwargs): response = super(DocumentViewSet, self).update( request, *args, **kwargs)