Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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": "http://localhost:8000/foo/bar?page=2",      "previous": null,      "results": [         {...}     ] } 

I would like to add extra counts like so:

{     "count": 45,     "10_mi_count": 10,     "20_mi_count": 30,     "30_mi_count": 45,     "next": "http://localhost:8000/foo/bar?page=2",      "previous": null,      "results": [         {...}     ] } 

The extra counts in this example are just how many of the objects have a field distance with a value less than the miles described in the key.

My issue is that I have no idea where the best place to extend and insert this behaviour is.

Ideally I'd like this to work whether or not the results are paginated, making no assumptions.

What I'm really after here is a nod in the right direction (and why that is the right place for it go).

I've checked the docs and can't find anything that describes how to add things like this, but I would be more than happy to be proven wrong on that score.

like image 418
Tom Manterfield Avatar asked Jun 11 '14 13:06

Tom Manterfield


People also ask

How do you pass extra context data to Serializers in Django REST Framework?

In function based views we can pass extra context to serializer with "context" parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with "self. context". From example, to get "exclude_email_list" we just used code 'exclude_email_list = self.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.


1 Answers

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!

like image 129
gaizka Avatar answered Sep 20 '22 17:09

gaizka