'CityListViewSet' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method

我与影子孤独终老i 提交于 2021-01-27 04:29:06

问题


I am assuming by the error in the title, once more here for clarity

'CityListViewSet' should either include a `serializer_class` attribute, 
or override the `get_serializer_class()` method.

that my serializer isn't connected to my view, which in my code it should be. I'm not really sure where the bug is in this one. I wonder if any of you have seen something similar?

Here is the code.

Router:

router.register(r'city-list', CityListViewSet, base_name='city-list')

view:

class CityListViewSet(viewsets.ReadOnlyModelViewSet):                 
    queryset = Venue.objects.values('city').distinct()
    serializer = CitySerializer(queryset, many=True)
    ordering_fields = ('city',)
    ordering = ('city',)

serializer:

class CitySerializer(serializers.ModelSerializer):    
    class Meta:
        model = City
        fields =('city',)

what is it that would be causing such an assertion error with the code seemly wired up correctly?


回答1:


The exception says it itself. You need a serializer_class attribute. You have serializer.




回答2:


i got this error when declared post method in view and trying to send post data without serialize, if you are doing the request from javascript i solved it using JSON.stringify()




回答3:


Here you used a different model name:

view:

class CityListViewSet(viewsets.ReadOnlyModelViewSet):     #(viewsets.ModelViewSet)             
queryset = City.objects.values('city').distinct()
serializer = CitySerializer(queryset, many=True)
ordering_fields = ('city',)
ordering = ('city',)

import -> from .serializers import TaskSerializers,CitySerializer

serializer:

class CitySerializer(serializers.ModelSerializer):    
class Meta:
    model = City
    fields =('city',)



回答4:


serializer = CitySerializer(queryset, many=True) 

The above line should be replaces with

serializer_class = CitySerializer(queryset, many=True)



来源:https://stackoverflow.com/questions/45157123/citylistviewset-should-either-include-a-serializer-class-attribute-or-overr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!