[Answered ]-Adding an action field to a post using Django Rest Framework

2๐Ÿ‘

โœ…

You need to add a SerializerMethodField() to always add a action key having value as createproject to the serialized representation of your object.

From the DRF docs on SerializerMethodField():

This is a read-only field. It gets its value by calling a method on
the serializer class it is attached to. It can be used to add any sort
of data to the serialized representation of your object
.

Your final code would be something like:

from models import Project
from rest_framework import serializers

class ProjectSerializer(serializers.ModelSerializer):
    """
    Serializes the Project model to send and receive valid JSON data.
    """
    # define a SerializerMethodField
    action = serializers.SerializerMethodField(method_name="get_data_for_action")    

    class Meta:
      model = Project
      fields = ('action', 'title', 'id', 'endDate', 'startDate', 'product')


    def get_data_for_action(self, obj):
        return "createproject" # always add this value in the 'action' key of serialized object representation
๐Ÿ‘คRahul Gupta

0๐Ÿ‘

The answer would be to use a CharField which would serialize and deserialize strings.

from models import Project
from rest_framework import serializers
class ProjectSerializer(serializers.ModelSerializer):
    """
    Serializes the Project model to send and receive valid JSON data.
    """
    action = serializers.CharField()
    class Meta:
      model = Project
      fields = ('action', 'title', 'id', 'endDate', 'startDate', 'product')

Then on your post you would either send {"action": "createproject"} as apart of your data. If you are trying to do it in your response then you would need to customize your view.

๐Ÿ‘คJared Mackey

Leave a comment