【问题标题】:Attach metadata for the json that rest framework returns为 rest 框架返回的 json 附加元数据
【发布时间】:2020-05-24 11:12:13
【问题描述】:

我的模型名为station,根据django rest framework做了API。

class Station(models.Model):
    filter_class = StationFilter
    name = models.CharField(unique=True,max_length=255)
    def __str__(self):
        return self.name

class StationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Station
        fields = ('id','name')

class StationViewSet(viewsets.ModelViewSet):
    queryset = Station.objects.all()
    serializer_class = StationSerializer

现在,它返回这样的Json,对应于表的cols。

{
    [ 
        {id: 1,name:"station1"},
        {id: 2,name:"station2"}
    ]
}

但是我想像这样附加这个 Json 的元数据。

{
    meta : {'time':"2020-02-02 00:00:00:",'apiName:"myapi"},
    items :[ 
        {id: 1,name:"station1"},
        {id: 2,name:"station2"}
    ]
}

有可能吗?或者我该怎么做??

【问题讨论】:

    标签: python json django django-rest-framework


    【解决方案1】:

    您需要覆盖 ViewSetlist 方法:

    class StationViewSet(viewsets.ModelViewSet):
        ...
    
        def list(self, request, *args, **kwargs):
            custom_data = {
                'list_of_items': StationSerializer(self.get_queryset(), many=true).data  #     this is the default result
            }
            custom_data.update({
                'meta': #your extra data
            })
            return Response(custom_data)
    

    更新:

    当您将过滤添加到您的ModelViewSet 时,您应该执行以下操作:

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        custom_data = {
            'list_of_items': self.get_serializer(queryset, many=True).data
        }
        custom_data.update({
            'meta': #your extra data
        })
        return Response(custom_data)
    

    【讨论】:

    • 非常感谢。它救了我!!还有一个问题...,我可以再问一个问题吗?我用过滤器。但是当我覆盖 list 时,这些类不起作用。 (更新文章)-
    • @whitebear 我更新了答案,希望它对你有用。
    猜你喜欢
    • 2017-08-21
    • 2023-03-25
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 2016-01-10
    • 1970-01-01
    相关资源
    最近更新 更多