Reputation: 7331
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?
Upvotes: 4
Views: 8727
Reputation: 37
In this method you need to use del method to delete dictionary items, because it will double the JSON output. So use this:
def to_representation(self, instance):
serializer = super().to_representation(instance)
serializer['Link'] = serializer['url']
serializer['Full Name'] = serializer['full_name']
del (serializer['url'], serializer['full_name'])
return serializer
Update, More elegant version:
def to_representation(self, instance):
mapping={
'old_field':'New Field',
...
}
serializer = super().to_representation(instance)
for old, new in mapping.items():
serializer[new] = serializer.pop(old, None)
return serializer
Upvotes: 0
Reputation: 47906
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')
Upvotes: 9