Django rest framework extra serializer field with get and post

I want to serialize a model and include an extra field. I want to use this serializer for a list, details, and creating views. In serialializer, I use the create, update, and get_field methods to configure the logic.

class ExampleSerializer(serializers.ModelSerializer): field = serializers.CharField() class Meta: model = Example fields = ("field", ...) 

When I add a new object, everything is correct (I can check the data of the user field), but when I get the object, the "field" does not exist in response.

EDIT: I want to set my own method for the serializer class to get the field. This is the best logical solution for me, and then set a custom method for the model.

Why is that? Is there a better solution for this (I don't want to use SerializerMethodField)?

+5
source share
1 answer

The field is not part of the model, due to which an error occurs. You can create this field write_only = True. Show field is an additional field.

 class ExampleSerializer(serializers.ModelSerializer): field = serializers.CharField(write_only=true) class Meta: model = Example fields = ("field", ...) 

or you can specify the initial value of the cross pond fields in this field.

  1. We can define a property method with this field name. You can include this field in the serializer as read-only, any data that you can return for this

     class Example(model.MOdels): @property def field(self): return #whatever you want to return 
  2. you can use the serilizermethod field.

      class ExampleSerializer(serializers.ModelSerializer): field = serializers.serializerMethod() class Meta: model = Example fields = ("field", ...) def get_field(self, obj): return obj.data 
+1
source

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


All Articles