Search code examples
pythondjangodjango-rest-frameworkdjango-serializer

get_field Not Working Django Rest Framework Serializer


In serializers.py

class WordSerializer(serializers.ModelSerializer):
    synonym = serializers.ListField(child=serializers.CharField(max_length=100), allow_null=True)

    class Meta:
        model = Word
        fields = ['word', 'id', 'user', 'definition', 'synonym', 'sentence', 'user', 'currently_studying']

when the original model has synonym value of synonym1\nsynonym2\nsynonym3, the synonym value in the serializer should return ['synonym1', 'synonym2', 'synonym3']. How can I do that?


Solution

  • It does not work for the synonym field because it is not possible to change the type of value from string to list but we can add a custom field to our json output. Here is an example. the key in the json output is "synonym_list" if you want to change it just change the name of the SerializerMethodField() and the method name ( get_ + new_name ) and change it in the fields list (Meta class) accordingly:

    class WordSerializer(serializers.ModelSerializer):
        synonym_list = serializers.SerializerMethodField()
    
        class Meta:
            model = Word
            fields = ['word', 'id', 'user', 'definition', 'synonym', 'sentence', 'user', 'currently_studying', 'synonym_list']
    
        def get_synonym_list(self, obj):
            return obj.synonym.split("\n")
    

    Does that work for you?