Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework extra serializer field with get and post

I want to serialize a model and include extra field. I want use this serializer for list, detail and create views. In serialializer I use create, update, and get_field methods to customize logic.

class ExampleSerializer(serializers.ModelSerializer):
    field = serializers.CharField()

    class Meta:
        model = Example
        fields = ("field", ...)

When I add new object everything is correct (I can validation custom field data), but when I get object, 'field' don't exists in response.

EDIT: I want set custom method on serializer class to get field. This is better logic solution for me then set custom method on model.

Why is it like that? Is exist better solution for this (I don't want use SerializerMethodField)?

like image 217
SmoQ Avatar asked Feb 08 '17 12:02

SmoQ


People also ask

How do you pass extra context data to Serializers in Django REST framework?

In function based views we can pass extra context to serializer with "context" parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with "self. context". From example, to get "exclude_email_list" we just used code 'exclude_email_list = self.

How do you make a field optional in a serializer?

By default it is set to False. Setting it to True will allow you to mark the field as optional during "serialization". Note: required property is used for deserialization.

What is difference between serializer and ModelSerializer?

The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .


1 Answers

The field is not part of the model, due to that it is coming the error. You can make that field write_only=True.Suppose field is extra field.

class ExampleSerializer(serializers.ModelSerializer):
   field = serializers.CharField(write_only=true)

   class Meta:
      model = Example
      fields = ("field", ...)

or you can give the source value the field cross ponds to which field.

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

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

     class ExampleSerializer(serializers.ModelSerializer):
         field = serializers.serializerMethod()
    
         class Meta:
            model = Example
            fields = ("field", ...)
          def get_field(self, obj):
              return obj.data
    
like image 175
aman kumar Avatar answered Sep 20 '22 05:09

aman kumar