【问题标题】:How do I place django rest nested serializer's fields to serializer?如何将 django rest 嵌套序列化程序的字段放置到序列化程序?
【发布时间】:2016-12-19 22:41:18
【问题描述】:

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

 [{
        "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'
        )

【问题讨论】:

  • 编写自定义序列化程序!

标签: django django-rest-framework


【解决方案1】:

假设您在序列化程序上定义了自定义 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

【讨论】:

  • 谢谢,它成功了。我正在尝试使用serializers.Field()
  • 我得到 TypeError:'ManyRelatedManager' 类型的对象不是 JSON 可序列化
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-21
  • 2018-07-04
  • 2017-01-16
  • 2016-01-03
  • 2014-12-21
相关资源
最近更新 更多