Tyrel Denison
Tyrel Denison

Reputation: 476

Adding an action field to a post using Django Rest Framework

I'm needing to add a some JSON to my serialized model using Django Rest Framework. It's purpose is simply to communicate to the api I am hitting what action to take. The json needs to be action:"createproject"

Below is an example of my serializer.

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.SOMETYPEOFFIELDIMGUESSING(data="createproject")


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

Upvotes: 1

Views: 1424

Answers (2)

Rahul Gupta
Rahul Gupta

Reputation: 47846

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

Upvotes: 2

Jared Mackey
Jared Mackey

Reputation: 4158

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.

Upvotes: 0

Related Questions