Hi Glenn,

You can make use of the `write_only` and `read_only` field arguments, in 
addition to `source`. eg, you should be able to do:

class StorySerializer(serializers.ModelSerializer):
    post_content = serializers.CharField(write_only=True, source='content')
    content = serializers.CharField(read_only=True)

That said, I'd argue against this, as it's kind of unexpected that you 
would create content with one name, and then read it from another. I would 
recommend just aliasing the `content` field as `post_content` in the 
serializer.

class StorySerializer(serializers.ModelSerializer):
    post_content = serializers.CharField(source='content')

Best,
Ryan
 

On Monday, September 25, 2017 at 6:06:21 PM UTC-4, Glenn Barney wrote:
>
> Hmm, no reply yet... maybe i'm not wording my question clearly.
>
> Requirements: When creating a Story, the input to my API must be 
> { "content": "Some content" }
>
> When getting the story, the output of my API must be:
> { "post_content": "Some content" }
>
>
> In the database mysql column, the column name must be "content". How can I 
> do this?
>
> One way this works is by coding this in the view, but I really don't like 
> this solution:
>
> def post(self, request, format=None):
>
>     data = request.data
>     data['post_content'] = request.data['content']
>     serializer = StorySerializer(data=request.data)
>     if serializer.is_valid():
>         serializer.save()
>         return Response(serializer.data, status=status.HTTP_201_CREATED)
>     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
>
>
> Is there a better way?
>
> On Monday, September 25, 2017 at 2:07:13 PM UTC-4, Glenn Barney wrote:
>>
>> So Im new to this and I am writing an api that takes a request with a 
>> field like this:
>>
>> { "content": "Some content" }
>>
>>
>> And I want to save this in  Story model in the db named "content" *but* i 
>> want it returned in the API with field post_content like so:
>>
>> { "post_content": "Some content" }
>>
>>
>> Here is my (stripped down) code:
>>
>> class StorySerializer(serializers.ModelSerializer):
>>
>>     post_content = serializers.CharField(source='content', required=False)
>>
>> class Meta:
>>     model = Story
>>     fields = ('post_content')
>>
>> class Story(models.Model):
>>     created = models.DateTimeField(auto_now_add=True)
>>     content = models.TextField()
>>
>>     class Meta:
>>         ordering = ('created',)
>>
>>
>> How do transform the "content" variable to "post_content"? I need it to 
>> be called post_content in the serializer for the data on the way out.
>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to