Django rest framework - how to add static field value for serializer

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

class QuestionSerializer(serializers.ModelSerializer): type = serializers.SerializerMethodField() @staticmethod def get_type(obj): return 'question' class Meta: model = Question fields = ('type',) 

But is there an easier way to do this without SerializerMethodField ?

+6
source share
4 answers

The only alternative would be to override to_representation and add the value there:

 def to_representation(self, obj): data = super().to_representation(obj) data['type'] = 'question' return data 

Not the best option.

+2
source

If you do not need to add a row to your model, it would be easier to add a static field to your model.

 class Question(models.Model): type = 'question' class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ('type',) 
+1
source

You can use serializers.HiddenField

 class QuestionSerializer(serializers.ModelSerializer): type = serializers.HiddenField(default='question') class Meta: model = Question fields = ('type',) 

http://www.django-rest-framework.org/api-guide/fields/#hiddenfield

+1
source

using 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

0
source

Source: https://habr.com/ru/post/1260535/


All Articles