gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:29:54 24 4
gpt4 key购买 nike

我需要使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com