Adding extra data to Django Rest Framework results for entire result set

后端 未结 4 1330
刺人心
刺人心 2020-12-14 15:42

I\'m using Django Rest Framework and need to add extra data to a result set. Specifically, where you would usually have:

{
    \"count\": 45, 
    \"next\":          


        
4条回答
  •  抹茶落季
    2020-12-14 16:04

    Since you seem to be using one of the ListViews from the Rest Framework, you could override the list() method in your class and set new values on the resulting data, like this:

        def list(self, request, *args, **kwargs):
            response = super().list(request, args, kwargs)
            # Add data to response.data Example for your object:
            response.data['10_mi_count'] = 10 # Or wherever you get this values from
            response.data['20_mi_count'] = 30
            response.data['30_mi_count'] = 45
            return response
    

    Notice that your class must inherit the ListModelMixin directly or via a GenericView from the Rest Framework API (http://www.django-rest-framework.org/api-guide/generic-views#listmodelmixin). I really don't know if it is the right way to do this, but it is a quick fix.

    Hope it helps!

提交回复
热议问题