Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the field name when using Django rest framework

I'm feeding serialized data from the Django rest framework to a Javascript pivot table on my site. If I have a variable called 'created_on', the DRF uses that as the field name. What I want to display in my pivot table is the label which will be converted to 'Created On'.

As an example, my output from DRF is the following:

[{"created_on": "2016-04-23"}, {"created_on": "2016-05-23"}]

What I want is:

[{"Created on": "2016-04-23"}, {"Created on": "2016-05-23"}]

Is this possible without me overriding the serialization process?

like image 598
Kritz Avatar asked Oct 29 '25 09:10

Kritz


1 Answers

No, its not possible (currently) without overriding the serialization process.

Why it is not possible?

This is because the alternate name which you want to use for created_on contains whitespace and its not possible to define a field in your serializer having whitespaces in it. Also, there is no functionality currently to provide alternate name for a field to be used in serialization process.

Possible Solution:

You can override the to_representation() method of your serializer and there add a Created On key having value equal to the value of created_on key. Then all the serialized objects will contain a key Created On.

class MySerializer(serializers.ModelSerializer):

    ...

    def to_representation(self, obj):
        primitive_repr = super(MySerializer, self).to_representation(obj)
        primitive_repr['Created On'] = primitive_repr['created_on']
        return primitive_repr  

What if the alternate name did not contain any whitespaces?

Had the alternate name did not contain any spaces between them, you could then have used SerializerMethodField() with source argument.

You could have done something like:

class MySerializer(serializers.ModelSerializer):

    alternate_name = serializers.SerializerMethodField(source='created_on')

    class Meta:
        model = MyModel
        fields = (.., 'alternate_name')
like image 97
Rahul Gupta Avatar answered Oct 31 '25 02:10

Rahul Gupta