get_serializer in generic list view (generics.ListCreateAPIView)

924 views
Skip to first unread message

Joar Leth

unread,
Jul 17, 2013, 5:51:52 AM7/17/13
to django-res...@googlegroups.com
I posted a question (http://stackoverflow.com/questions/17649903/implement-get-serializer-in-generic-list-view-generics-listcreateapiview-in-dj) on StackOverflow the other day, but there doesn't seem to be alot of activity there, so I'll post it here too.

I have a PageSerializer that inherits from DynamicFieldsModelSerializer which I copied from the docs (http://django-rest-framework.org/api-guide/serializers.html#dynamically-modifiying-fields). To initialize the serializer from my generic view I implemented get_serializer. For my detail view (which inherits from generics.RetrieveUpdateDestroyAPIView) this works fine, but when I try to initialize my PageSerializer in the list view (which inherits from generics.RetrieveUpdateDestroyAPIView) I get the following error:

'PageList' should either include a 'serializer_class' attribute,
or use the 'model' attribute as a shortcut for automatically generating
a serializer class.

Here's my get_serializer implementation (which I implemented in the list view as well as in the detail view)

def get_serializer(self, instance=None, data=None, files=None, many=False, partial=False):
    fields = None
    if self.request.method == 'GET':
        query_fields = self.request.QUERY_PARAMS.get("fields", None)

        if query_fields:
            fields = tuple(query_fields.split(','))

    return PageSerializer(instance=instance, data=data, files=files, many=many, partial=partial, fields=fields) 

Judging from the error message get_serializer doesn't seem go get used. Is there a different way to achieve this for a list view? I haven't managed to find any hints as to how get_serializer should be used.


Joar Leth

unread,
Jul 22, 2013, 11:34:56 AM7/22/13
to django-res...@googlegroups.com
I used the default pagination, which meant get_serializer was never called (Seems a bit like a bug to me, but I guess it could also be viewed as a missing feature). Either way, I realized that I can probably achieve the same thing using get_serializer_context() (or from the serializer, but I usually prefer to do things like that in the view).


--
You received this message because you are subscribed to a topic in the Google Groups "Django REST framework" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-rest-framework/8qor1_wHMgA/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages