Home > Net >  api call method and viewset
api call method and viewset

Time:01-31

I try to create a api call:

class CategoryViewSet(viewsets.ModelViewSet):
    serializer_class = CategorySerializer
    queryset = Category.objects.all() 
    
    @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)

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:


AttributeError at /djangoadmin/groups/mainGroups/

Got AttributeError when attempting to get a value for field `name` on serializer `CategorySerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'name'.

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),   
    
]

Category model:

class Category(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)
    description = models.TextField(max_length=1000)
    images = models.ImageField(upload_to="photos/categories")
    category = models.ForeignKey(
        "Category", on_delete=models.CASCADE, related_name='part_of', blank=True, null=True)
    date_create = models.DateTimeField(auto_now_add=True)
    date_update = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "category"
        verbose_name_plural = "categories"

    def __str__(self):
        return self.name

Question: how to create api method in main url?

CodePudding user response:

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(mainGroups, many=True)
        
        return Response(serializer.data)
  • Related