Add DynamicFieldsModelSerializer

This commit is contained in:
Saqibur Rahman 2023-11-26 16:57:10 +06:00
parent 7c92ccba79
commit f6dd8cc021
1 changed files with 23 additions and 0 deletions

23
common/serializers.py Normal file
View File

@ -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)