rest-framework之url控制

自定义路由(原始方式)

 url(r'^publish/$', views.Publish.as_view()),
 url(r'^publish/(?P<pk>\d+)$', views.PublishDetailView.as_view()),
class Publish(models.Model):
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)
from rest_framework.serializers import ModelSerializer
from app01 import models
from rest_framework.views import APIView
from rest_framework.response import Response
# Create your views here.
class PublishSerializers(ModelSerializer):
    class Meta:
        model = models.Publish
        fields="__all__"

class Publish(APIView):
    def get(self,request):
        publish_list=models.Publish.objects.all()
        pb = PublishSerializers(publish_list,many=True)
        return Response(pb.data)


    def post(self,request):
        pb = PublishSerializers(data=request.data)
        if pb.is_valid():
            pb.save()
            return Response(pb.data)
        else:
            return Response(pb.errors)


class PublishDetailView(APIView):
    def get(self,request,pk):
        publish_obj = models.Publish.objects.filter(pk=pk).first()
        pb =PublishSerializers(publish_obj,many=False)
        return Response(pb.data)

    def put(self,request,pk):
        publish_obj = models.Publish.objects.filter(pk=pk).first()
        pb = PublishSerializers(data=request.data,instance=publish_obj)
        if pb.is_valid():
            pb.save()
            return Response(pb.data)

    def delete(self,request,pk):
        models.Publish.objects.filter(pk=pk).delete()
        return Response("")

半自动路由(视图类继承ModelViewSet)

    # 半自动路由
    url(r'^publish/$', views.PublishView.as_view({'get': 'list', 'post': 'create'})),
    url(r'^publish/(?P<pk>\d+)/$',views.PublishView.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
from rest_framework.viewsets import ModelViewSet
class PublishView(ModelViewSet):
    queryset=models.Publish.objects.all()
    serializer_class=PublishSerializers

全自动路由自动生成路由

前提是视图类里面必须继承ModelViewSet

from django.conf.urls import url,include

# SimpleRouter 自动生成两条路由
# DefaultRouter自动生成四条路由
# router=SimpleRouter()
router=DefaultRouter()
# 两个参数,一个是匹配的路由,一个是视图中写的CBV的类 router.register('publish',views.PublishView) url(r'',include(router.urls))
from rest_framework.viewsets import ModelViewSet
class PublishView(ModelViewSet):
    queryset=models.Publish.objects.all()
    serializer_class=PublishSerializers

 

 SimpleRouter下生成的路由rest-framework之url控制

DefaultRouter下生成的路由rest-framework之url控制

 

 

路径上加上rest-framework之url控制显示的是json格式的信息

rest-framework之url控制这两种都可以

 

上一篇:11 django模型层_多表练习


下一篇:应用程序在Android Market上发布,但在某些手机中不可见