我想要Django rest框架的json响应,所以我有这样的Json Response:

[
    {
        "id": 1,
        "TitleEnglish": "Tiny Talents Program",
        "TitleArabic": "Tiny Talents Program",
        "DescriptionEnglish": "Timing: 8:00 am till 1:00 pm",
        "DescriptionArabic": "Timing: 8:00 am till 1:00 pm",
        "CategoryEnglish": "Art & Education ",
        "CategoryArabic": "Art & Education ",
        "Date": "2015-05-07",
        "Status": true,
        "Image": "--"
    }
]

但我需要这样的回应:
{
"data": [
    {
        "id": 1,
        "TitleEnglish": "Tiny Talents Program",
        "TitleArabic": "Tiny Talents Program",
        "DescriptionEnglish": "Timing: 8:00 am till 1:00 pm",
        "DescriptionArabic": "Timing: 8:00 am till 1:00 pm",
        "CategoryEnglish": "Art & Education ",
        "CategoryArabic": "Art & Education ",
        "Date": "2015-05-07",
        "Status": true,
        "Image": "--"
    }
       ]
}

我的序列化器代码是:
class PromotionSerializer(serializers.HyperlinkedModelSerializer):
    CategoryEnglish  = serializers.CharField(read_only=True, source="Category.TitleEnglish")
    CategoryArabic  = serializers.CharField(read_only=True, source="Category.TitleArabic")
    class Meta:
        model = Promotion
        fields = ('id', 'TitleEnglish', 'TitleArabic', 'DescriptionEnglish', 'DescriptionArabic', 'CategoryEnglish','CategoryArabic', 'Date','Status','Image')

最佳答案

我通过更改 View 来解决了我的问题:

我添加了一个列表方法,我的问题解决了:

def list(self, request):
    queryset = Promotion.objects.all()
    serializer_class = PromotionSerializer(queryset, many=True)
    serialized_data =  {'data': serializer_class.data}
    return Response(serialized_data)

10-08 13:01