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
- [Answered ]-Form action isn't triggering at all
- [Answered ]-Restrict foreign key values according to request.user in django
- [Answered ]-Pyinstaller 3.2 with django 1.10.1
Source:stackexchange.com