简体   繁体   中英

Django rest framework APIView register route

I am not able to register an APIView to my url routes.

Code from views :

class PayOrderViewSet(APIView):
    queryset = PayOrder.objects.all()

Code from urls :

router = routers.DefaultRouter()
router.register(r'document/payorder', PayOrderViewSet)

This newly created url doesn't exist at all.

What is solution for this?

Routers won't work with APIView . They only work with ViewSets and their derivatives.

You likely want:

class PayOrderViewSet(ModelViewSet):

Routers and APIViews (generic or otherwise) are two different ways to create API endpoints. Routers work with viewsets only.

In your code, you are although trying to create a viewset for a router your code is extending APIView class.

Your problem will be taken care by what @linovia has suggested in his asnwer. I would suggest it will be good idea to understand the difference between those two.

GenericViewSet inherits from GenericAPIView but does not provide any implementations of basic actions. Just only get_object, get_queryset.

ModelViewSet inherits from GenericAPIView and includes implementations for various actions. In other words you dont need implement basic actions as list, retrieve, create, update or destroy. Of course you can override them and implement your own list or your own create methods.

Read More about viewsets and Generic Class Based APIViews :

For ViewSet you use router for url register and for APIView you need to add path to urlpatterns . Next example should help:

from post.api.views import UniquePostViewSet
from django.urls import path, include
from rest_framework.routers import DefaultRouter

from post.api.views import FileUploadView

router = DefaultRouter()
router.register('UniquePost', UniquePostViewSet, base_name='uniquepostitem')

urlpatterns = [
    path('demo', FileUploadView.as_view(), name='demo'),  
]

urlpatterns += router.urls

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