Django RESTFrame 路由问题

路由分为3中:

  a. 自定义路由

  b. 半自动路由

  c. 全自动路由

 

1.自定义路由

urls.py

from django.conf.urls import url, include
from web.views import s11_render

urlpatterns = [
    url(r'^test/$', s11_render.TestView.as_view()),
    url(r'^test\.(?P<format>[a-z0-9]+)$', s11_render.TestView.as_view()),
    url(r'^test/(?P<pk>[^/.]+)/$', s11_render.TestView.as_view()),

]

views.py

 1 from rest_framework.views import APIView
 2 from rest_framework.response import Response
 3 from .. import models
 4 
 5 
 6 class TestView(APIView):
 7     def get(self, request, *args, **kwargs):
 8         print(kwargs)
 9         print(self.renderer_classes)
10         return Response('...')

 

2.半自动路由

urls.py

from django.conf.urls import url, include
from web.views import s10_generic

urlpatterns = [
    url(r'^test/$', s10_generic.UserViewSet.as_view({'get': 'list', 'post': 'create'})),
    url(r'^test/(?P<pk>\d+)/$', s10_generic.UserViewSet.as_view(
        {'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})),   # 各个请求,对应view类中,要执行的方法
]

views.py

from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers
from .. import models


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = "__all__"


class UserViewSet(ModelViewSet):
    queryset = models.UserInfo.objects.all()
    serializer_class = UserSerializer

 

3.全自动路由

urls.py

from django.conf.urls import url,include

from rest_framework import routers   # 用于全自动路由的类
router = routers.DefaultRouter()       # 用于全自动路由
router.register(r'test', pagination.TestView,base_name='my_test')


urlpatterns = [
    url(r'^', include(router.urls),
]

 

views.py

 1 from rest_framework.viewsets import ModelViewSet
 2 from rest_framework import serializers
 3 from .. import models
 4 
 5 
 6 class UserSerializer(serializers.ModelSerializer):
 7     class Meta:
 8         model = models.User
 9         fields = "__all__"
10 
11 # 在这里指定数据库的类、以及序列化的类之后,就能自动存取数据了
12 # 执行get方法,就自动取到数据
13 # 执行post,就能向当前model表存入数据
14 class TestView(ModelViewSet):
15     queryset = models.User.objects.all()
16     serializer_class = UserSerializer

 

posted on 2018-03-06 11:08  Mr_Bai  阅读(200)  评论(0编辑  收藏  举报

导航