Django Rest Framework自定义字段只有一对值(没有fieldname作为dict键)

时间:2015-07-23 09:33:07

标签: python django django-rest-framework django-serializer

您好我想在REST服务上只提供没有键的值对:

查看我的 serializers.py

 class TranslationSerializer(serializers.ModelSerializer):
        translated_term = serializers.CharField(read_only=True)

        class Meta:
                model = Translation
                fields = ('language','translated_term')

class VocabSerializer(serializers.ModelSerializer):
       ...
        translates = TranslationSerializer(many=True, read_only=True)
       ...

        class Meta:
        model = Vocab
        fields = ( ..., 'translates',...)

结果如下:

"translates": [
        {
            "language": "EN",
            "translated_term": "Chair"
        }
        {
            "language": "IT",
            "translated_term": "asd"
        }
    ],

如您所见,此结果将该字段的名称显示为该字段值旁边的dict键。 但我希望有一个不同的结构。如下所示:

    "translates": [
        {
            "EN": "Chair", "IT":"asd"
        }
    ],

此示例显示了一对键/值,其中key是语言字段值,dict的值是已翻译字段的值。

我怎样才能只显示'语言'字段用'翻译'没有字段名称的字段?

2 个答案:

答案 0 :(得分:7)

您可以通过自定义list serializer

来实现它
class TranslationListSerializer(serializers.ListSerializer):
    def to_representation(self, data):
        r = super().to_representation(data)

        return { item['language']: item['translated_term'] for item in r }

class TranslationSerializer(serializers.ModelSerializer):
    translated_term = serializers.CharField(read_only=True)

    class Meta:
            model = Translation
            fields = ('language','translated_term')
            list_serializer_class = TranslationListSerializer

答案 1 :(得分:1)

通过为序列化程序创建自定义to_representation函数,您可以控制字典表示。

 class TranslationSerializer(serializers.ModelSerializer):
        translated_term = serializers.CharField(read_only=True)

        def to_representation(self, instance):
            # get the instance -> Dict of primitive data types
            representation = super(TranslationSerializer, self).to_representation(instance)

            # manipulate returned dictionary as desired
            language = representation.pop('language')
            translated_term = representation.pop('translated_term')

            # repackage
            repackaged = {language: translated_term}

            return repackaged

        class Meta:
                model = Translation
                fields = ('language','translated_term')

这将以

的格式生成JSON
"translates": [
        {
            "EN": "Chair"
        },
            "IT": "asd"
        }
    ],

但是,这并不是您希望它看起来的样子,也许是一种定制的“代表性”。对于VocabSerializer可以预先形成。