OverflowingTheGlass
OverflowingTheGlass

Reputation: 2434

How to Add JSON Array to DRF Response

I have a DRF ListAPIView that returns this:

count: 35652
next: "https://platform/events/?format=json&page=2"
previous: null
results: (50) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
__proto__: Object

What do I need to add to the view or serializer to return this?

count: 35652
next: "https://platform/events/?format=json&page=2"
previous: null
results: (50) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
filter_data: ['filter element 1', 'filter element 2']
__proto__: Object

Upvotes: 1

Views: 455

Answers (1)

Sasja Vandendriessche
Sasja Vandendriessche

Reputation: 749

Since you use ListAPIView you can override the list() method, bear in mind that this method needs to return a Response object (also take a look at the source code) (inspired by this SO answer).

   def list(self, request, *args, **kwargs):
        response = super().list(request, args, kwargs)

        # you can add the data that you need in the response
        response.data['filter_data'] = ['filter element 1', 'filter element 2']

        return response

Also, don't forget that .data contains already serialized data.

Upvotes: 2

Related Questions