Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何仅使用一个serializerMethodField获得两个值_Python_Django_Django Rest Framework - Fatal编程技术网

Python 如何仅使用一个serializerMethodField获得两个值

Python 如何仅使用一个serializerMethodField获得两个值,python,django,django-rest-framework,Python,Django,Django Rest Framework,当“内容”字段被排除时,我想在“内容”字段中添加“未包含内容”,否则为“内容包含” 序列化程序.py class PostSerializer(serializers.ModelSerializer): sth = serializers.SerializerMethodField() class Meta: model = Post fields = ('id', 'sth', 'content', 'created',) def g

当“内容”字段被排除时,我想在“内容”字段中添加“未包含内容”,否则为“内容包含”

序列化程序.py

class PostSerializer(serializers.ModelSerializer):
    sth = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ('id', 'sth', 'content', 'created',)

    def get_sth(self, obj):
        return 
回应我想要得到的

[
    {
      "id": "1",
      "sth": "content contained",
      "content": "a",
      "created": "2020-01-23"
    },
    {
      "id": "3",
      "sth": "NOT content contained",
      "created": "2020-01-22"
    },
]
我怎样才能得到上面这样的回复

drf有一个名为**.to_表示的功能**

类后序列化程序(serializers.ModelSerializer): sth=serializers.SerializerMethodField()


类似的东西可能会起作用

to_表示法中修改它,如下所示

class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = ('id', 'content', 'created',)

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if content is not included:
           data.update({'sth': "content contained"})
        else:
           data.update({'sth': "NOT content contained"})
        return data

您必须根据您的系统设置
内容不包含
条件。

您如何*排除*仅针对某些项目的
内容
字段?我使用了.values()函数。
class Meta:
    model = Post
    fields = ('id', 'sth', 'content', 'created',)

def get_sth(self, obj):
    return 

def valdiate_content(self,value):
    if self.sth == 'content contained':
         return self.value
def to_internal_value(self,data):
    if self.sth === 'NOT content contained':
         data.pop('content')
    return super(PostSerializer, self).to_internal_value(data)
class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = ('id', 'content', 'created',)

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if content is not included:
           data.update({'sth': "content contained"})
        else:
           data.update({'sth': "NOT content contained"})
        return data