Multiple Choice Field Equivalent

1,505 views
Skip to first unread message

Yigit Guler

unread,
Mar 13, 2014, 10:42:47 AM3/13/14
to django-res...@googlegroups.com
Hi,

Right now i discovered that there is no multiple choice field in Django Rest Framework. Is this done by purpose? ChoiceField does not accept many=True parameter eighter. 

Do you have any advice or examples for simuating MCF in Rest Framework?

Thank you!

Yigit

Yigit Guler

unread,
Mar 13, 2014, 11:14:22 AM3/13/14
to django-res...@googlegroups.com
As this was an urgent need, i wrote a very simple MultipleChoiceField:


class MultipleChoiceField(serializers.WritableField):
    """
    A field that behaves like multiple choice field of Django forms.
    """
    def from_native(self, data):
        if isinstance(data, list):
            for item in data:
                if not item in self.choices:
                    raise serializers.ValidationError("The item you entered is not in the allowed items list.")
            return data
        else:
            raise serializers.ValidationError("Please provide a valid list.")

    def to_native(self, value):
        return value

    def __init__(self, choices=None, *args, **kwargs):
        self.choices = dict(choices)
        super(MultipleChoiceField, self).__init__(*args, **kwargs)


But i still can't believe that there is no multiple choice field on DRF. This must be on purpose. I am very curious about it :)

13 Mart 2014 Perşembe 16:42:47 UTC+2 tarihinde Yigit Guler yazdı:

Tom Christie

unread,
Mar 13, 2014, 12:33:22 PM3/13/14
to django-res...@googlegroups.com
> But i still can't believe that there is no multiple choice field on DRF.

It's not that surprising, easily missed the first time around when building the initial serializer fields, and all these things need to be actually written, tested, documented and reviewed by someone. - Sounds like a really great potential pull request tho :)

I also noticed the the ChoicesField really isn't really adequately documented, and furthermore that it might be nice if choices fields  multiple choice fields could accept regular lists rather than only accepting two-tuple choice lists.
Given that we're dealing with API inputs rather than *necessarily* form inputs I'm often likely to want a `score = serializers.ChoicesField(choices=[1,2,3])`.
Seems to me that it'd be nicer for the end user if we could treat that the same as `choices=[('1', 1), ('2', 2), ('3', 3)]`
Reply all
Reply to author
Forward
0 new messages