序列化为自定义嵌套字典

时间:2019-05-17 20:47:46

标签: python django django-rest-framework

首先,我认为显示一些代码以帮助理解我要实现的目标很重要。

这是我的序列化器:

class ExerciseRoutineSerializer(serializers.ModelSerializer):
    exercise = ExerciseSerializer()

    class Meta:
        model = ExerciseRoutine
        fields = '__all__'

    def to_representation(self, obj):
        representation = super().to_representation(obj)
        exercise_representation = representation.pop('exercise')
        for key in exercise_representation:
            representation[key] = exercise_representation[key]

        return representation

class RoutineSerializer(serializers.ModelSerializer):
    exercises = ExerciseRoutineSerializer(many=True)

    class Meta:
        model = Routine
        fields = '__all__'

基本上,我需要在RoutineSerializer中以某种有序数据结构包含演习字段。目前,这是我的输出:

[
    {
        "id": 1,
        "routines": [
            {
                "id": 1,
                "exercises": [
                    {
                        "id": 1,
                        "index": 0,
                        "rest_time": 60,
                        "repetition_goal": 10,
                        "equipment": [
                            {
                                "id": 1,
                                "equipment": "Fixed Bar"
                            }
                        ],
                        "name": "Pull up"
                    }
                ],
                "name": "RoutineName",
                "routine_type": "Regular"
            }
        ],
        "name": "WorkoutName"
    }
]

根据ExerciseRoutineSerializer返回练习,很棒。但是,按照我需要的顺序,我在模型中创建了一个“索引”字段来管理其顺序。是这样的:

[
    {
        "id": 1,
        "routines": [
            {
                "id": 1,
                "exercises": {
                        0 : {"id": 1, "rest_time": 60, "repetition_goal": 10,"equipment": [{..}], "name": "Pull up"},
                        1 : {"id": 13, "rest_time": 60, "repetition_goal": 10,"equipment": [{..}], "name": "Anotherexericse"}
                },
                "name": "RoutineName",
                "routine_type": "Regular"

            }
        ],
        "name": "WorkoutName"
    }
]

在这种情况下,ExerciseRoutineSerializer将返回字典而不是列表,并且该字典的键将是“索引”字段,其余所有将进入值。老实说,我对如何实施一无所知,因为这是我第一个使用DRF的项目

0 个答案:

没有答案