4

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.

4

1 回答 1

1

您看到的错误是因为您没有在视图上声明serializer_classormodel属性。如果你没有指定那些你必须重写get_serializer_class()以告诉视图使用哪个序列化程序。

你还说:

但是当我尝试在列表视图(继承自 generics.RetrieveUpdateDestroyAPIView)中初始化我的 PageSerializer 时,我收到以下错误:

列表视图应该继承自其中一个通用列表视图ListCreateAPIView,而不是单个对象视图RetrieveUpdateDestroyAPIView

于 2013-10-31T20:35:35.840 回答