Как получить два значения, просто используя один serializerMethodField - PullRequest
1 голос
/ 24 января 2020

Когда поле «содержимое» исключено, я хочу добавить «НЕ содержимое содержится» в поле «sth», иначе «содержимое содержит»

serializers.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"
    },
]

Как я могу получить ответ, как указано выше.

Ответы [ 3 ]

1 голос
/ 24 января 2020

Измените его следующим способом to_representation

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

Вы должны установить условие content is not included в соответствии с вашей системой.

0 голосов
/ 24 января 2020

Класс PostSerializer (serializers.ModelSerializer): sth = serializers.SerializerMethodField ()

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)

Что-то подобное может работать

0 голосов
/ 24 января 2020

drf имеет одну из функций, названную ** .to_representation ** https://www.django-rest-framework.org/api-guide/serializers/#baseserializer

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

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

    def get_sth(self, obj):
        return 

    def to_representation(self, instance):
        ** here you can modify the your data what you want to represent **
        return [
            {
                "id": "1",
                "sth": "content contained",
                "content": "a",
                "created": "2020-01-23"
            },
            {
                "id": "3",
                "sth": "NOT content contained",
                "created": "2020-01-22"
            },
       ]
...