其他分享
首页 > 其他分享> > 半自动路由和全自动路由

半自动路由和全自动路由

作者:互联网

url控制:
三种:
-最原始的
-半自动(必须继承ViewSetMixin)
-url(r'^books/$', views.Book.as_view({'get':'get_all'})),
-全自动(自动生成路由,必须继承自ModelViewSet)(不建议用)

 

-半自动(必须继承ViewSetMixin)

from rest_framework.views import APIView
from rest_framework.viewsets import ViewSetMixin
from app01 import models
from app01 import MySer
from rest_framework.response import Response
class Book(ViewSetMixin, APIView):
    def get_all(self, request):
        return Response()

    def get_one(self, request, pk):
        return Response()

 

from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
from rest_framework import routers
# # 实例化产生一个对象
# router=routers.DefaultRouter()
# router.register('^books',views.Book)
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^books/$', views.Book.as_view({'get':'get_all'})),
    url(r'^books/(?P<pk>\d+)', views.Book.as_view({'get':'get_one'})),
    # url('', include(router.urls)),

-全自动(自动生成路由,必须继承自ModelViewSet)(不建议用)

from rest_framework.viewsets import ModelViewSet
-继承它ModelViewSet
-写一个视图类,视图类中定义两个变量
class Book(ModelViewSet):
    queryset = models.Book.objects.all()
    serializer_class = MySer.BookSerializers

from rest_framework import routers
#自动生成路由,需要继承ModelViewSet 才可以使用
# rou = routers.SimpleRouter()
rou = routers.DefaultRouter()
rou.register('BookModelViewSet',views.BookModelViewSet)
urlpatterns += rou.urls

 

继承了ModelViewSet 不使用自动路由
-路由:(两条路由):
# re_path('BookModelViewSet/(?P<pk>\d+)', views.BookModelViewSet.as_view(actions={'get':'retrieve','put':'retrieve','delete':'distroy'})),
# path('BookModelViewSet/', views.BookModelViewSet.as_view(actions={'get':'list','post':'create'})),

标签:views,url,get,ModelViewSet,Book,半自动,import,全自动,路由
来源: https://www.cnblogs.com/dzs894330350/p/16064745.html