[Fixed]-How do I create an additional non-model CharField for a DRF 3 serializer?

1👍

I believe you have the answer in the DRF docs: http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

SerializerMethodField This is a read-only field…It can be used to add any sort of data to the serialized representation of your object.

from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    days_since_joined = serializers.SerializerMethodField()

    class Meta:
        model = User

    def get_days_since_joined(self, obj):
        return (now() - obj.date_joined).days

Update: Now for your case:

class PostSerializer(serializers.ModelSerializer):

    postType = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ('id', 'usersVoted', 'post')
        read_only_fields = ('id', 'owner')

    def get_postType():
        return "posts"
👤Radek

0👍

You got that exception because read_only_fields are supposed to be from the model while postType isn’t a model field.

Leave a comment