Skip to content

Instantly share code, notes, and snippets.

@shuternay
Last active August 9, 2020 16:25
Show Gist options
  • Save shuternay/1c3d8c5572fca09690aaad7ddb6d12a4 to your computer and use it in GitHub Desktop.
Save shuternay/1c3d8c5572fca09690aaad7ddb6d12a4 to your computer and use it in GitHub Desktop.
DRF CaseInsensitiveSerializer
import copy
from django.http.request import QueryDict
from django.utils.datastructures import CaseInsensitiveMapping
from rest_framework.serializers import empty
class CaseInsensitiveSerializer(serializers.Serializer):
"""
Serializer which treats parameters names as case-sensitive.
"""
def __init__(self, instance=None, data=empty, **kwargs) -> None:
fields = self.get_fields()
field_names = CaseInsensitiveMapping({field_name: field_name for field_name, field in fields.items()})
if isinstance(data, QueryDict):
new_data = QueryDict('', mutable=True, encoding=data.encoding)
for key, value in data.lists():
key = field_names.get(key, key)
new_data.setlist(key, copy.deepcopy(value))
elif data is empty:
new_data = data
else:
# Note: we may loose repeated keys at that moment
new_data = {field_names[name]: value for name, value in data.items()}
super().__init__(instance, new_data, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment