Django rest问题:使用listApiView获取额外的操作

2024-03-29 12:12:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Django REST API框架进行一个项目。当我在本地运行项目时,会出现以下错误:

File "/home/asad/PycharmProjects/microshop/venv/lib/python3.8/site-packages/rest_framework/routers.py", line 153, in get_routes
    extra_actions = viewset.get_extra_actions()
AttributeError: type object 'CustomerListAPIViewSet' has no attribute 'get_extra_actions'

我在Google和StackOverflow上搜索,但没有找到任何解决方案

序列化程序.py

class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = ['name', 'phone_number', 'address', ]

视图.py

class CustomerListAPIViewSet(generics.ListAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer

url.py

from django.urls import path, include
from accounts_app.views import CustomerListAPIViewSet
from rest_framework import routers

router = routers.DefaultRouter()

router.register(r'customer/', CustomerListAPIViewSet)

urlpatterns = router.urls

Tags: 项目frompyimportactionsrestgetframework
1条回答
网友
1楼 · 发布于 2024-03-29 12:12:52

您的问题在于视图的命名。这造成了混乱

实际上,您正在创建一个APIView子类。但是你把它命名为ViewSet。您可以向rest_框架路由器注册ViewSet类,而不是APIView

您可以进行以下更改以使视图可运行

视图文件:

class CustomerListAPIView(generics.ListAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer

URL文件:

from django.urls import path, include
from accounts_app.views import CustomerListAPIView

urlpatterns = [
    path(r'^customer/', CustomerListAPIView.as_view(), name='customer-list')
]

另一种方法是定义一个实际的ViewSet类,但结构会有所不同

相关问题 更多 >