Api call method and viewset

I try to create a api call:

class CategoryViewSet(viewsets.ModelViewSet):
    serializer_class = CategorySerializer
    queryset = Category.objects.all() 
    
    @action(methods=['get'], detail=False)
    def mainGgroups(self,request):        
        mainGroups = Category.objects.filter(category_id__isnull=True) 
        serializer = self.get_serializer_class()(mainGroups)
        
        return Response(serializer.data)

serializer:

class CategorySerializer(serializers.ModelSerializer):
    animals = AnimalSerializer(many=True)
    
    class Meta:
        model = Category
        fields = ['id','category_id','name', 'description', 'animals']

So the main url works: http://127.0.0.1:8000/djangoadmin/groups/

But if I go to: http://127.0.0.1:8000/djangoadmin/groups/maingGroups/

I get this error:


{
    "detail": "Not found."
}

urls.py:

router = routers.DefaultRouter()
router.register('groups', CategoryViewSet)   


urlpatterns = [
    path('', include(router.urls))
]

and urls.py of admin looks:

from django.contrib import admin
from django.urls import path, include


urlpatterns = [
    path("djangoadmin/", include('djangoadmin.urls')),
    path("admin/", admin.site.urls),   
    
]

Question: how to create api method in main url?

I think your problem is with how you are instantiating your serializer class. When you are saying:

    @action(methods=['get'], detail=False)
    def mainGroups(self,request):        
        mainGroups = Category.objects.filter(category_id__isnull=True) 
        serializer = self.get_serializer_class()(mainGroups)
        
        return Response(serializer.data)

The many parameter, when looking at your error message, seems to be defaulting to False, whereas you want to serialize many of these objects.

I would change the instantiation to:

    @action(methods=['get'], detail=False)
    def mainGroups(self,request):        
        mainGroups = Category.objects.filter(category_id__isnull=True) 
        serializer = self.get_serializer_class(mainGroups, many=True)
        
        return Response(serializer.data)
Back to Top