如何在Django Rest Framework中用id替换对象?

时间:2016-05-03 12:24:50

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

我有这些序列化器:

class ASerializer(serializers.ModelSerializer):
    name = serializers.CharField()

    class Meta:
        model = AModel
        fields = ('id','name')


class BSerializer(serializers.HyperlinkedModelSerializer):
    a = ASerializer(partial=True)
    name = serializers.CharField()

    class Meta:
        model = ‌‌BModel
        fields = ('id','name', 'a')


class CSerializer(serializers.HyperlinkedModelSerializer):
    b = BSerializer(partial=True)
    created_by = UserSerializer(required=False) 
    message = serializers.CharField()

    class Meta:
        model = CModel
        fields = ('id','b', 'created_by', 'message')

以下是我发送给服务的数据:

data_json = {
    "id": '1',
    "b": '2',
    "created_by":'3',
    "message": 'Hello world'
}

我希望响应数据包含在所有嵌套的完美对象中,而不仅仅是嵌套对象id。

如何使用ID替换B对象或created_by对象以创建C对象?

1 个答案:

答案 0 :(得分:0)

尝试此示例,序列化程序定义为:

class ASerializer(serializers.ModelSerializer):
    name = serializers.CharField()

    class Meta:
        model = A
        fields = ('id', 'name')


class BSerializer(serializers.HyperlinkedModelSerializer):
    name = serializers.CharField()
    a = ASerializer(partial=True, many=True)

    class Meta:
        model = B
        fields = ('id', 'name', 'a')


class CSerializer(serializers.HyperlinkedModelSerializer):
    name = serializers.CharField()
    b = BSerializer(partial=True, many=True)

    class Meta:
        model = C
        fields = ('id', 'name', 'b')

并且viewset定义为:

class CViewSet(viewsets.ModelViewSet):
    queryset = C.objects.all()
    serializer_class = CSerializer

这是上面viewset返回的json示例:

{
    "id": 2,
    "name": "c2",
    "b": [
        {
            "id": 2,
            "name": "b2",
            "a": [
                {
                    "id": 2,
                    "name": "a2"
                },
                {
                    "id": 3,
                    "name": "a3"
                }
            ]
        },
        {
            "id": 3,
            "name": "b3",
            "a": [
                {
                    "id": 3,
                    "name": "a3"
                }
            ]
        }
    ]
},