Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How (if it is possible) can a custom field be added to a paginated response in Django / REST?

Suppose I have a view like the following:

class FooView(ListAPIView):
    serializer_class = FooSerializer
    pagination_class = FooPagination

Which returns a typical paginated response such as:

{
     "count":2,
     "next":null,
     "previous":null,
     "results":[
      {
          "id":1,"name":"Josh"
       },
      {
          "id":2,"name":"Vicky"
      }]
}

How (if it is possible) can a custom field be added to this response so the result is as follows?

{
    "count":2,
    "next":null,
    "previous":null,
    "custom":"some value",
    "results":[
    {
         "id":1,"name":"Josh"
     },
     {
         "id":2,"name":"Vicky"
      }]
}

Assuming that "some value" is calculated in an appropriate method and stored, such as:

def get_queryset(self):
    self.custom = get_custom_value(self)
    # etc...
like image 869
gornvix Avatar asked Dec 07 '25 07:12

gornvix


1 Answers

Another possible solution is add custom fields to your response, don't need override Pagination class

def list(self, request, *args, **kwargs):
        response = super(YourClass, self).list(request, args, kwargs)
        # Add data to response.data Example for your object:
        response.data['custom_fields'] = 10 # Or wherever you get this values from
        return response
like image 59
ittus Avatar answered Dec 08 '25 23:12

ittus