简体   繁体   中英

Django rest framework error object X has no attribute 'get_extra_actions'

I am wanting to add some search functionality to my API and I followed this simple guide but I'm still getting the error

type object 'ClientViewSet' has no attribute 'get_extra_actions'


My setup

Versions

  • Django: 2.2.5
  • Django Rest Framework: 3.11.0
  • Python: 3.8.2

models.py

class Client(models.Model):
    phone = models.CharField(max_length=10)

urls.py

router = routers.DefaultRouter()
router.register(r'clients', ClientViewSet)

urlpatterns = [
    path('api/', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

serializers.py

class ClientSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Client
        fields = '__all__'

views.py

class ClientViewSet(generics.ListAPIView):
    queryset = Client.objects.all()
    serializer_class = ClientSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['phone']

"You've called it a viewset, but that doesn't make it one; you inherit from APIView which is a standalone generic view, not a viewset.

A viewset needs to inherit from viewsets.ViewSet."

https://stackoverflow.com/a/49721133/8932675

To build off the answer provided here , a ViewSet needs to inherit from a ViewSet and the ListAPIView class does not inherit from ViewSet .

A way to get this to work, however, is to change the inherited class from ListAPIView to ModelViewSet like this:

class ClientViewSet(viewsets.ModelViewSet):
    queryset = Client.objects.all()
    serializer_class = ClientSerializer
    filter_backends = [DjangoFilterBackend]
    filter_fields = ['phone']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM