django API调用方法和视图集

xv8emn3q  于 2023-01-31  发布在  Go
关注(0)|答案(1)|浏览(134)

我尝试创建一个api调用:

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)

串行器:

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

所以主url是有效的:http://127.0.0.1:8000/djangoadmin/groups/
但如果我去:http://127.0.0.1:8000/djangoadmin/groups/maingGroups/
我得到这个错误:

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

管理员的www.example.com看起来: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),   
    
]

类别型号:

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

问:如何在主url中创建api方法?

9udxz4iz

9udxz4iz1#

我认为你的问题在于你是如何示例化你的序列化器类的。当你说:

@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)

在查看错误消息时,many参数似乎默认为False,而您希望序列化其中的许多对象。
我会将示例化更改为:

@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)

相关问题