Django Rest Framework - 获取列表中的完整相关对象

时间:2015-02-25 14:10:29

标签: python django rest django-rest-framework

我是Django Rest Framework的新手,我尝试使用DRF序列化(相关)对象列表。

我有以下型号:

class Answer(models.Model):
   value = models.CharField(max_length=128)

class User(models.Model):
   name = models.CharField(max_length=128)
   age = models.PositiveIntegerField()

class UserAnswer(models.Model):
    user = models.ForeignKey(User)
    answer = models.ForeignKey(Answer)

我试图得到的结果就是这样:

[
    {
     "name": "myName1",
     "answers": [
        {
          "value": "myFirstAnswer"
        },
        {
          "value": "mySecondAnswer"
        },
        {
          "value": "myThirdAnswer"
        },
        ]
    },
    {
     "name": "myName2",
     "answers": [
        {
          "value": "myFirstAnswer"
        },
        {
          "value": "mySecondAnswer"
        },
        {
          "value": "myThirdAnswer"
        },
        ]
    }
]

我现在正试图这样做:

class UserAnswerSerializer(serializers.ModelSerializer):
    answers = AllUserAnswersSerializer(many=True, read_only=True)
    class Meta:
        model = User
        fields = ('name', 'answers')

然后我得到以下结果:

[
    {
        "name": "myName1"
    }, 
    {
        "name": "myName2"
    }
]

当我尝试这样做时:

class UserAnswerSerializer(serializers.ModelSerializer):
    answers = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    class Meta:
        model = User
        fields = ('name', 'answers')

然后我得到以下结果(再次举例):

[
    {
     "name": "myName1",
     "answers": [
        1,
        2,
        3
        ]
    },
    {
     "name": "myName2",
     "answers": [
        4,
        5,
        6
        ]
    }
]

我很难完成这项工作,希望有人可以告诉我如何将主键转换为实际对象!

谢谢!

1 个答案:

答案 0 :(得分:8)

删除序列化程序中答案字段的明确定义,然后添加depth=1。它应该是这样的:

class UserAnswerSerializer(serializers.ModelSerializer):
    class Meta:
        depth = 1
        model = User
        fields = ('name', 'answers')

深度信息:http://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization