Skip to content

Instantly share code, notes, and snippets.

@dbrgn
Last active Sep 13, 2018
Embed
What would you like to do?
Moved to https://github.com/dbrgn/drf-dynamic-fields
@zhanglc
Copy link

zhanglc commented Dec 25, 2014

Hi

I use the DynamicFieldsMixin in DRF3, but get the KeyError for the line below

fields = self.context['request'].QUERY_PARAMS.get('fields')

is any suggestion? thanks

@dbrgn
Copy link
Author

dbrgn commented Jan 27, 2015

@zhanglc: Sorry, I'm not involved in the project anymore. Back with DRF2 it seemed to work. Maybe the way the context works has changed in the meantime?

@jayarnielsen
Copy link

jayarnielsen commented May 1, 2015

I just tried this with Django 1.8 and rest framework 3. Works brilliantly, thank you.

@X17
Copy link

X17 commented Jun 11, 2015

In 3.0 replace "QUERY_PARAMS.get" with query_params.get

fields = self.context['request'].query_params.get('fields', None)

and in views pass request in context to serilizer, example

def get(self, request, format=None):
event = Event.objects.all()
** serializer = EventSerializer(event, many=True, context={'request': request}) **
filter = EventFilter
return Response(serializer.data)

@lucasdavid
Copy link

lucasdavid commented Jul 13, 2015

@X17, any suggestions on how to use this without implementing the get() method? (I'm using a ModelViewSet)

@rawbeans
Copy link

rawbeans commented Jul 21, 2015

@lucasdavid The request is included by default in the context with ModelViewSet (look at the definition of get_serializer and get_serializer_context in generics.py). However, I had to add the following line:

if not self.context:
        return

before

 fields = self.context['request'].query_params.get('fields', None)

Without this, I would get an error when the server was starting up because there was no request object.

@dbrgn
Copy link
Author

dbrgn commented Sep 30, 2016

I just published this as a package on PyPI! https://github.com/dbrgn/drf-dynamic-fields

@wonderbeyond
Copy link

wonderbeyond commented Feb 27, 2017

#Mark for my next google search# Another implementation: https://github.com/wimglenn/djangorestframework-queryfields

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment