kelvinwong-ca / django-select-multiple-field

Select multiple choices in a single Django model field
Other
34 stars 25 forks source link

Don't know how to use it with DRF #17

Open mpvillafranca opened 8 years ago

mpvillafranca commented 8 years ago

I've got some models with attributes which are SelectMultipleField. I'm using Django Rest Framework to serialize that models and send the data to an AngularJS app, but I've got a problem when I'm trying to update that fields via JSON. When I get the data from the server, I'm receiving an array of strings, but when I sent the update data back to the server with the same format, I'm getting an error: "This isn't a valid option". I've also tried to parse the data to strings splited by commas but it doesn't work either.... Any ideas of what I'm doing wrong?

class Hueco(models.Model):

    class ProteccionType(DjangoChoices):
        Ninguno = ChoiceItem(label=u'Ninguno', value='ninguno')
        Retranqueo = ChoiceItem(label=u'Retranqueo', value='retranqueo')
        Voladizo = ChoiceItem(label=u'Voladizo', value='voladizo')
        Lateral_izquierdo = ChoiceItem(label=u'Lateral Izquierdo', value='lateral_izquierdo')
        Lateral_derecho = ChoiceItem(label=u'Lateral Derecho', value='lateral_derecho')
        Toldo = ChoiceItem(label=u'Toldo', value='toldo')
        Lamas_verticales = ChoiceItem(label=u'Lamas Verticales', value='lamas_verticales')
        Lamas_horizontales = ChoiceItem(label=u'Lamas Horizontales', value='lamas_horizontales')
        Laminas = ChoiceItem(label=u'Láminas', value='laminas')
        Cortinas = ChoiceItem(label=u'Cortinas', value='cortinas')

    tipo_proteccion = SelectMultipleField(
        max_length=150,
        choices=ProteccionType.choices,
        default=ProteccionType.Ninguno
    )
class HuecoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Hueco
        fields = ('id', 'tipo_proteccion' )
metalhand91 commented 6 years ago

Add new serializer field:

class LegacyMultipleChoiceField(serializers.MultipleChoiceField):
    def to_internal_value(self, value):
        return ','.join(value)

serializer:

class HuecoSerializer(serializers.ModelSerializer):
    tipo_proteccion = LegacyMultipleChoiceField(choices=your_choises)

    class Meta:
        model = Hueco
        fields = ('id', 'tipo_proteccion' )