Home > Software design >  Error when I put choices in Charfield in a Serializer which is not based on Model - Django Rest Fram
Error when I put choices in Charfield in a Serializer which is not based on Model - Django Rest Fram

Time:09-30

I make a serializer, which is not based on a model and one of the fields is a charfield in which I want to put a specific choices. Is that possible?

The error I get when I put the code:

TypeError: init() got an unexpected keyword argument 'choices'

STATUS_TYPES = (
    ('', ''),
    ('male', 'male'),
    ('female', 'female')
)

class SomeSerializer(serializers.Serializer):
    gender = serializers.CharField(max_length=100, choices=GENDER_TYPES)

CodePudding user response:

To use choice field in Django Rest Framework use : ChoiceField or MultipleChoiceField instead of Charfield(..., choices=(...))

In your case :

class SomeSerializer(serializers.Serializer):
    gender = serializers.ChoiceField(choices=GENDER_TYPES)

CodePudding user response:

There is a workaround for this by using SerializerMethodField. I assume the first element in GENDER_TYPES tuple is the source and the second element is what you want it to be.

GENDER_TYPES = (
    ('', ''),
    ('male', 'male'),
    ('female', 'female')
)

class SomeSerializer(serializers.Serializer):
    gender = serializers.SerializerMethodField()
    
    def get_gender(self, obj):
        return next(filter(lambda gt: gt[0] == obj['gender'], GENDER_TYPES))[1]
  • Related