django-multiselectfield
django-multiselectfield copied to clipboard
DRF integration issue
Hello,
There is a problem when using MultiSelectField combined with DRF. I've got multiselect field declared in my model:
my_field = MultiSelectField(choices=TYPES)
And serializer for model:
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = (
...,
'my_field'
)
There is an issue that API sometimes returns list and sometimes returns string value. List is returned when there is more that one element in database. String is returned when there is 0 or 1 element.
DRF uses ChoiceField to serialize value for multiselect field and that seems to be issue.
Thanks for reporting this issue, please feel free to contribute with a Pull Request.
Thanks for reporting this issue, please feel free to contribute with a Pull Request.
@tomasgarzon Hi,I've also encountered this issue when returning field with only one choice being selected.
The expected result should be returning a single element list when there's only one choice was selected, but I got string value, like @Blejwi said.
So do you have any idea how to solve this issue? Thank you.
For those who come here for a trade-off solution, I overwrite the to_representation method to process the data format issue.
First, define your own serializer:
class CustomSerializer(serializers.ModelSerializer):
def to_representation(self, instance):
ret = super().to_representation(instance)
ret = self.make_list(instance, ret)
return ret
def make_list(self, instance, ret):
for fd in instance._meta.get_fields():
if fd.__class__ is MultiSelectField:
ret[fd.attname] = [ret[fd.attname]] if not isinstance(ret[fd.attname], list) else ret[fd.attname]
# here you can add whatever other logic you want
return ret
Then inherit the CustomSerializer in your own serializer like:
class MySerializer(CustomSerializer):
pass
Every MultiSelectFieldwill be converted to list by DRF thorough to_representation method automatically.
For now, this is the best solution I can find.
Hope this can help other users.@tomasgarzon
Potential fix: https://github.com/encode/django-rest-framework/pull/8082
@sdsy888 Thanks a lot! I was struggling with the same issue. Kudos again! Also, thanks to @yuekui for contributing a solution to DRF.
Please open a PR with any additions, including better DRF support, that would be useful to other users.