如何将django rest嵌套序列化程序的字段放入序列化程序?

时间:2016-12-19 22:41:19

标签: django django-rest-framework

在以下代码中,template是外键。模板是嵌套的序列化程序来询问序列化程序。

 [{
        "pk": 15,
        "template": {
            "question_type": 1,
            "question": "What is your age ?",
            "answer_type": 1,
            "available_choices": []
        },
        "order": 1,
        "mandatory": true
    }]

我想表现的是:

[
{
    "pk": 15,
    "question_type": 1,
    "question": "What is your age?",
    "order": 1,
    "answer_type": 1,
    "mandatory": true,
    "available_choices": []
}]

如何显示这样的嵌套序列化数据字段?

这是我的序列化程序类:

class TemplateSerializer(serializers.ModelSerializer):
    available_choices = ChoiceSerializer(many=True)

    class Meta:
        model = Template
        fields = (
            'question_type', 'question', 'answer_type',
            'available_choices'
        )
class ASerializer(serializers.ModelSerializer):
    template = TemplateSerializer()

    class Meta:
        model = A
        fields = (
            'pk', 'template', 'order', 'mandatory'
        )

1 个答案:

答案 0 :(得分:0)

假设您在序列化程序上定义了自定义create()和update()函数。

class ASerializer(serializers.ModelSerializer):

    question_type = serializers.ReadOnlyField(source='template.question_type', read_only=True)
    question = serializers.ReadOnlyField(source='template.question', read_only=True)
    answer_type = serializers.ReadOnlyField(source='template.answer_type', read_only=True)
    available_choices = serializers.ReadOnlyField(source='template.available_choices', read_only=True)

    class Meta:
        model = A