Multiplechoices Fields does not preserve order
This behavior looks intentional due to the usage of a set instead of a list in MultipleChoicesField.
This results in an unexpected behavior to the user while selecting a list of values, since they will be used in the document without a deterministic order.
A good solution may be to overwrite the Multiplechoices forcing the usage of lists:
class OrderedMultipleChoiceField(serializers.MultipleChoiceField):
def to_internal_value(self, data):
if isinstance(data, str) or not hasattr(data, "__iter__"):
self.fail("not_a_list", input_type=type(data).__name__)
if not self.allow_empty and len(data) == 0:
self.fail("empty")
return [
super(serializers.MultipleChoiceField, self).to_internal_value(item)
for item in data
]
def to_representation(self, value):
return [
self.choice_strings_to_values.get(str(item), item) for item in value
]
Or using a ListField as described here:
dataColumns = serializers.ListField(
child=serializers.MultipleChoiceField(
choices=allowed_choices,
allow_blank=False),
source="data_Columns"
)
Edited by Israel Teixeira