一、自定义路由(原始方式)
urls.py
url(r'^books/$', views.Books.as_view()),
url(r'^books/(?P<pk>d+)$', views.BookDetail.as_view()),
views.py
from rest_framework.views import APIView
from app01 import models
from app01.myser import BookSerializers
from rest_framework.response import Response
class Books(APIView):
def get(self, request, *args, **kwargs):
response = {'code': 100, 'msg': '查询成功'}
ret = models.Book.objects.all()
book_ser = BookSerializers(instance=ret, many=True)
response['data'] = book_ser.data
return Response(response)
def post(self, request, *args, **kwargs):
response = {'code': 100, 'msg': '新增成功'}
book_ser = BookSerializers(data=request.data)
if book_ser.is_valid():
book_ser.save()
else:
response['code'] = 101
response['msg'] = book_ser.errors # 错误信息被response序列化出来返回前端
return Response(response)
class BookDetail(APIView):
def get(self, request, pk, **kwargs): # id是有名分组传过来的id
response = {'code': 100, 'msg': '查询成功'}
ret = models.Book.objects.filter(pk=pk).first()
book_ser = BookSerializers(instance=ret, many=False)
response['data'] = book_ser.data
return Response(response)
def put(self, request, pk, **kwargs):
response = {'code': 100, 'msg': '修改成功'}
ret = models.Book.objects.filter(pk=pk).first()
book_ser = BookSerializers(instance=ret, data=request.data) # 修改需要传两个参数
if book_ser.is_valid():
book_ser.save() # 校验通过,如果不是空,调update方法, 如果是空,调create方法
# 原因是ModelSerializer 重写了这两个方法
else:
response['code'] = 101
response['msg'] = book_ser.errors
return Response(response)
def delete(self, request, pk, **kwargs):
response = {'code': 100, 'msg': '删除成功'}
models.Book.objects.filter(pk=pk).delete()
return Response(response)
二、第二种方式(视图类继承ModelViewSet)
urls.py:视图类中只要继承了ViewSetMixin,路由必须这样写
url(r'^publish/$', views.Publish.as_view({'get':'list','post':'create'})),
url(r'^publish/(?P<pk>d+)/$', views.Publish.as_view({'get':'retrieve','put':'update','delete':'destroy'})),
views.py
from rest_framework.serializers import ModelSerializer
class PublishSerializers(ModelSerializer):
class Meta:
model = models.Publish
fields = "__all__"
from rest_framework.viewsets import ModelViewSet
class Publish(ModelViewSet): # ModelViewSet中继承了ViewSetMixin
queryset = models.Publish.objects.all()
serializer_class = PublishSerializers
三、第三种方式(自动生成路由)
使用SimpleRouter与DefaultRouter大前提是视图类中必须继承了ModelViewSet
myser.py
from rest_framework.serializers import ModelSerializer
from app01 import models
class PublishSerializers(ModelSerializer):
class Meta:
model = models.Publish
fields = '__all__'
views.py
from rest_framework.viewsets import ModelViewSet
from app01 import models
from app01.myser import PublishSerializers
# 自动生成路由
class Publish(ModelViewSet): # 必须要继承ModelViewSet
queryset = models.Publish.objects.all()
serializer_class = PublishSerializers
1、SimpleRouter 自动生成两条路由
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from app01 import views
from rest_framework.routers import SimpleRouter
# 自动生成两条路由
router = SimpleRouter()
router.register('publish', views.Publish)
# router.register('book', views.Book) 可以注册很多个
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include(router.urls)),
]
前端展示
访问所有图书
2、DefaultRouter 自动生成四条路由
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from app01 import views
from rest_framework.routers import DefaultRouter
# 自动生成四条路由
router = DefaultRouter()
router.register('publish', views.Publish)
# router.register('book', views.Book) 可以注册很多个
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include(router.urls)),
]
前端展示