How to map an input field to a different field in a django serializer
|August 14, 2014||Posted by forumadmin under TechQns||
This is something I have be trying to find for days but to no avail.
I’m working an a rest based api using django that will be integrating with a legacy database. I want to validate the input and a serializer seems like it is ideal for this task. However, some of the field names coming in from the api don’t match up with the field names in the database. So for example, if I have a field called title in the database but called headline in the api how can I get the serialize to see headline as valid and automatically map to title.
I know I could just alter the data before sending it to the serializer but that seems like a bad idea that will lead to errors down the road.
So far most of the answers I have found on this subject involve mapping a object from data to a different name. But that is the opposite of what I want to do. I have tried using the source attribute in a CharField but that hasn’t worked.
title = serializers.CharField(source='headline')
I’ve also tried the reverse of this.
headline = serializers.CharField(source='title')
I understand that I may have to add fields in the meta class but if I have to update the serializer every time the data model changes then I might as well do my own code to serialize as this makes using a Model serializer pointless.
|Asked By – truest.wizzle||Read Answers|