继承ViewSetMixin,它放在前面(好处,跟某个功能相关的,可以写在一起),
这样写的好处,一个book可以响应两个get请求
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): # 过滤条件,从GET中取出来 response = {'status': 100, 'msg': '查询成功'} book_list = models.Book.objects.all() # 这个是序列化数据 ser = MySer.BookSerializers(instance=book_list, many=True) # 如果是校验数据要传request.data,也就是从前台传过来的数据,不能按位置传参,需要按照关键字传参data=request.data response['data'] = ser.data return Response(response) def get_one(self, request, pk): response = {'status': 100, 'msg': '查询成功'} book = models.Book.objects.all().filter(pk=pk).first() if book: ser = MySer.BookSerializers(instance=book, many=False) response['data'] = ser.data else: response['status'] = 101 response['msg'] = '您要查询的数据不存在' return Response(response)
from app01 import models from rest_framework import serializers class BookSerializers(serializers.ModelSerializer): class Meta: model = models.Book fields = '__all__'
from django.db import models class Book(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) price = models.CharField(max_length=32) def __str__(self): return self.name
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)),
这种方法可以快速写出5个接口
from rest_framework.viewsets import ModelViewSet -继承它ModelViewSet -写一个视图类,视图类中定义两个变量 class Book(ModelViewSet): queryset = models.Book.objects.all() serializer_class = MySer.BookSerializers -路由:(两条路由): 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'})),
响应器:(一般不需要配置)
-返回用Response
url控制:
三种:
-最原始的
-半自动(必须继承ViewSetMixin)
-url(r'^books/$', views.Book.as_view({'get':'get_all'})),
-全自动(自动生成路由,必须继承自ModelViewSet)(不建议用)