djangodjango-rest-frameworkdjango-serializer

Change ModelSerializer field key with function


I have a simple Django Rest Framework ModelSerializer for a model that has a field "name". I want to serialize it so the name is the value and its cleaned name is the key in the following way:

"results": [
    {
        "mymodel1" : "My Model 1"
    },
    {
        "mymodel2" : "My Model 2"
    }]

I currently have:

class ModelSimpleSerializer(serializers.ModelSerializer):

  keyname = serializers.SerializerMethodField('get_model_keyname')
  class Meta:
    model = myModel
    fields = (
      'keyname',
    )
  def get_model_keyname(self,obj):
    keyname = obj.name
    keyname = keyname .lower()
    keyname = keyname .replace(" ", "")
    return keyname

which returns:

"results": [
    {
        "keyname" : "mymodel1"
    },
    {
        "keyname" : "mymodel2"
    }]

Any ideas?

Thank you!


Solution

  • Try this

    class ModelSimpleSerializer(serializers.Serializer):
        def to_representation(self, obj):
            keyname = obj.name.lower().replace(" ", "")
            return {
                keyname: obj.name,
            }
    

    Note that this will be read only serializer. But It will meet your requirements

    objects = myModel.objects.all()
    
    ModelSimpleSerializer(objects.first()).data
    # {"mymodel1" : "My Model 1"}
    
    ModelSimpleSerializer(objects, many=True).data
    # [{"mymodel1" : "My Model 1"}, {"mymodel2" : "My Model 2"}]