Skip to content

Commit

Permalink
feat: add option to duplicate list key (#1) (#2)
Browse files Browse the repository at this point in the history
Release-As: 0.1.0

Co-authored-by: mikko.nieminen <mikko.nieminen@bihealth.de>
  • Loading branch information
holtgrewe and mikkonie committed Jul 18, 2023
1 parent 304fd82 commit 5b7d9fe
Showing 1 changed file with 4 additions and 0 deletions.
4 changes: 4 additions & 0 deletions drf_keyed_list/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class KeyedListSerializer(ListSerializer):
"not_a_dict": _('Expected a dict of items but got type "{input_type}".'),
"empty": _("This dict may not be empty."),
}
_duplicate_key = False

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
Expand All @@ -18,6 +19,7 @@ def __init__(self, *args, **kwargs):
meta, "keyed_list_serializer_field"
), "Must provide a field name at keyed_list_serializer_field when using KeyedListSerializer"
self._keyed_field = meta.keyed_list_serializer_field
self._duplicate_key = meta.duplicate_list_key

def to_internal_value(self, data):
if not isinstance(data, dict):
Expand All @@ -34,4 +36,6 @@ def to_internal_value(self, data):

def to_representation(self, data):
response = super().to_representation(data)
if self._duplicate_key:
return {v[self._keyed_field]: v for v in response}
return {v.pop(self._keyed_field): v for v in response}

0 comments on commit 5b7d9fe

Please sign in to comment.