Django-rest-framework:禁用嵌套字段

时间:2015-11-07 15:46:40

标签: json django django-rest-framework

我正在使用Django REST Framework和我

我有一个名为QuestionSerializer的序列化程序,我在响应中指定了3个字段:id,json和说明。 由于我在PostgreSQL数据库中使用JSONField,我的json字段是存储在db中的json,我使用JSONSerializerField来渲染它。

这是我的代码:

class JSONSerializerField(serializers.Field):
    """ Serializer for JSONField -- required to make field writable"""
    def to_internal_value(self, data):
        return data
    def to_representation(self, value):
        return value

class QuestionSerializer(serializers.ModelSerializer):
    content = JSONSerializerField(source='json')

    class Meta:
        model = Question
        fields = ('id', 'content', 'explanation')

所以,每次我使用QuestionSerializer时,我的回答都是这样的:

{
    "id": 1,
    "content": {
        "question": "question",
        "answers": [
            {"answer": "answer"},
            {"answer": "answer"},
            {"answer": "answer"},
            {"answer": "answer"},
            {"answer": "answer"}
        ],
    }
    "explanation": "explanation"
}

但我需要删除“内容”字段以获得如下响应:

{
    "id": 1,
    "question": "question",
    "answers": [
        {"answer": "answer"},
        {"answer": "answer"},
        {"answer": "answer"},
        {"answer": "answer"},
        {"answer": "answer"}
    ],
    "explanation": "explanation"
}

我应该做什么?

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以使content write_only字段并使用它来存储数据。添加两个新的read_only字段并使用它们来获取如下数据:

class QuestionSerializer(serializers.ModelSerializer):
    content = JSONSerializerField(source='json', write_only=True)
    question = serializers.SerializerMethodField()
    answers = serializers.SerializerMethodField()

    class Meta:
        model = Question
        fields = ('id', 'content','question', 'answers', 'explanation')

    def get_questions(self, obj):
        return obj.content['question']

    def get_answers(self, obj):
        return obj.content['answers']

答案 1 :(得分:1)

我找到了正确的解决方案。我删除了内容'字段和JSONSerializerField类,我开始使用SerializerMethodField处理我的json。

class QuestionSerializer(serializers.ModelSerializer):
    question = serializers.SerializerMethodField()
    answers = serializers.SerializerMethodField()

    class Meta:
        model = Question
        fields = ('id', 'question', 'answers', 'explanation')

    def get_question(self, obj):
        return obj.json['question']

    def get_answers(self, obj):
        return obj.json['answers']

答案 2 :(得分:0)

您应该更新您的字段,以便它直接返回/阅读内容:

class JSONSerializerField(serializers.Field):
    """ Serializer for JSONField -- required to make field writable"""
    def to_internal_value(self, data):
        return {'content': data}
    def to_representation(self, value):
        return value['content']