python - 使用 Django Rest Framework 将操作字段添加到帖子中

标签 python json django django-rest-framework

我需要使用 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()始终将值为 createprojectaction 键添加到对象的序列化表示中。

来自 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/

相关文章:

python - 由于文档中的示例已损坏,如何在 SymPy 中以数值方式求解非线性方程组?

python - 使用 Boost.python 构建 Hello World

python - 查找区间索引的有效方法

sql - Postgresql 中的 JSON 输出

python - 弹性查询失败,并显示以下错误异常:TransportError(400,u'search_phase_execution_exception',u'无法解析查询[*/abc *]')

python - 如何使用 Python 制作嵌套 JSON 对象

python - 在 Ansible 中使用 JINJA2 从 JSON 中提取带条件的嵌套字典值

python - manage.py runserver 打开pycharm而不是running server

python - 如何向 django 管理面板添加自定义 View 和操作?

python - 如何使用 Django choicefield 动态设置选项?