我需要使用 Django Rest Framework 将一些 JSON 添加到我的序列化模型中。它的目的只是向 api 传达我正在执行的操作。 json 需要是 action:"createproject"
下面是我的序列化器的示例。
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')
最佳答案
您需要添加SerializerMethodField()
始终将值为 createproject
的 action
键添加到对象的序列化表示中。
来自 SerializerMethodField()
上的 DRF 文档:
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.
您的最终代码将类似于:
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
关于python - 使用 Django Rest Framework 将操作字段添加到帖子中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32532372/