Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest framework - how to add a static field value for a serializer

Tags:

I need to add a static field to my serializer. It should always return the same value, regardless of the passed object. Currently I implemented it like so:

class QuestionSerializer(serializers.ModelSerializer):
    type = serializers.SerializerMethodField()

    @staticmethod
    def get_type(obj):
        return 'question'

    class Meta:
        model = Question
        fields = ('type',)

But is there a simpler way to do it, without the SerializerMethodField?

like image 872
kurtgn Avatar asked Nov 29 '16 16:11

kurtgn


1 Answers

using a ReadOnlyField worked for me:

class QuestionSerializer(serializers.ModelSerializer):
    type = serializers.ReadOnlyField(default='question')

    class Meta:
        model = Question
        fields = ('type',)

https://www.django-rest-framework.org/api-guide/fields/#readonlyfield

like image 196
David Schumann Avatar answered Oct 12 '22 02:10

David Schumann