drf--ViewSet -第二波 进阶版 ----含更高度封装类ModelViewSet
https://www.bilibili.com/video/BV1z5411D7BQ?p=19&vd_source=caabcbd2a759a67e2a3de8acbaaf08ea
view.py
GenericViewSet 是继承了ViewSet
from sers.models import Book
from rest_framework import serializers
from rest_framework.mixins import ListModelMixin,CreateModelMixin,UpdateModelMixin,DestroyModelMixin,RetrieveModelMixin
from rest_framework.generics import RetrieveDestroyAPIView
from rest_framework.viewsets import GenericViewSet
class BookSerializers(serializers.ModelSerializer):
class Meta:
model=Book
fields = "__all__"
# ListModelMixin中的list方法获取所有数据 ----所以在路由处制定该方法即可
# CreateModelMixin中的create方法新增一条数据 ----所以在路由处制定该方法即可
# RetrieveModelMixin中retrieve方法,为根据id查看单条 ----所以在路由处制定该方法即可
# UpdateModelMixin中update方法,为根据id更新某条 ----所以在路由处制定该方法即可
# DestroyModelMixin中destroy方法,为根据id删除某条 ----所以在路由处制定该方法即可
class BookView(GenericViewSet,ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin):
# 获取所有书籍---操作数据库
queryset = Book.objects.all()
# 序列化模型(序列化器)
serializer_class = BookSerializers
url.py
urlpatterns = [
path('admin/', admin.site.urls),
# 新
url('^book/$', views.BookView.as_view({"get":"list","post":"create"})),
# 新
# 加有名分组?P<pk>
url('^book/(?P<pk>\d+)/$', views.BookView.as_view({"get":"retrieve","put":"update","delete":"destroy"})),
]
-----------ModelViewSet
实际就是 ModelViewSet 是继承了GenericViewSet,ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin6个方法 ,不用写那么多类集成,写一个ModelViewSet就够了
# ListModelMixin中的list方法获取所有数据 ----所以在路由处制定该方法即可
# CreateModelMixin中的create方法新增一条数据 ----所以在路由处制定该方法即可
# RetrieveModelMixin中retrieve方法,为根据id查看单条 ----所以在路由处制定该方法即可
# UpdateModelMixin中update方法,为根据id更新某条 ----所以在路由处制定该方法即可
# DestroyModelMixin中destroy方法,为根据id删除某条 ----所以在路由处制定该方法即可v
# ModelViewSet 是继承了GenericViewSet,ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin6个方法
from rest_framework.viewsets import ModelViewSet
class BookSerializers(serializers.ModelSerializer):
class Meta:
model=Book
fields = "__all__"
class BookView(ModelViewSet):
# 获取所有书籍---操作数据库
queryset = Book.objects.all()
# 序列化模型(序列化器)
serializer_class = BookSerializers
踩坑:
如果用modelViwSet url那边一定要用 re_path
from django.urls import re_path as url
urlpatterns = [
# 巡检任务 增、删、改、查
url('^task/$', patroltaskviews.PatrolTaskViews.as_view({"get":"list","post":"create"})),
url('^task/(?P<pk>\d+)/$', patroltaskviews.PatrolTaskViews.as_view({"get":"retrieve","put":"update","delete":"destroy"})),
]