From f6dd8cc0213abeb8f0508df6b6214c7382b80d67 Mon Sep 17 00:00:00 2001 From: Saqibur Rahman Date: Sun, 26 Nov 2023 16:57:10 +0600 Subject: [PATCH] Add DynamicFieldsModelSerializer --- common/serializers.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 common/serializers.py diff --git a/common/serializers.py b/common/serializers.py new file mode 100644 index 0000000..c6d344d --- /dev/null +++ b/common/serializers.py @@ -0,0 +1,23 @@ +from rest_framework.serializers import ModelSerializer + + + +class DynamicFieldsModelSerializer(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().__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)