Skip to content

Instantly share code, notes, and snippets.

@dbrgn
Last active September 13, 2018 20:44
Show Gist options
  • Save dbrgn/4e6fc1fe5922598592d6 to your computer and use it in GitHub Desktop.
Save dbrgn/4e6fc1fe5922598592d6 to your computer and use it in GitHub Desktop.
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?

@jnlsn
Copy link

jnlsn 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

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

@rawbeans
Copy link

@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

#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