Q:

Django. REST Framework. Rename SerializerMethodField()

In the django rest framework, I have a serializer, it takes fields from the model, combines it under one tag, and displays it in xml. Everything is simple.
I understand how it works. But what I don’t understand is how to rename the parent tag.
I will show:
#serializers.py

class kvSerializerLivingSpace(serializers.ModelSerializer):
unit = serializers.CharField(default='qm')
    class Meta:
        model = kv
        fields = ['unit', 'value']

class kvSerializer(serializers.ModelSerializer):
living_space = serializers.SerializerMethodField()

    class Meta:
    model = kv
    fields = ['living_space']

    def get_living_space(self, obj):
    return kvSerializerLivingSpace(obj).data

I need living_space through a hyphen. To make it look like living-space
I know that i can rename tags as follows:
   def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields.update({
            'living-space': kvSerializerLivingSpace()
        })

But this does not work for serializers.SerializerMethodField()
Thank!

A:

Try
self.fields.update({
    'living-space': serializers.SerializerMethodField(method_name='get_living_space')
})

The code you had does not work because you were using kvSerializerLivingSpace without a source for the data thus DRF tries to pull the data from model field that has the same name as the serializer field (living-space), which does not exist.
If you really want that method to just serialize the whole object, you don't need it. Instead, you can do:
self.fields.update({
    'living-space': kvSerializerLivingSpace(source='*')
})

The star means the whole object is used as a source.
For more info: https://www.django-rest-framework.org/api-guide/fields/#source

