django mixin 操作方法

这是 Django 中 mixin 的导包

from rest_framework.response import Response                        # 获取返回值
from rest_framework.generics import GenericAPIView            # 把 APIview 改成这个                
from rest_framework.mixins import 
ListModelMixin,                                     # 展示数据
CreateModelMixin,                                    # 添加数据
UpdateModelMixin,                                    # 修改数据
DestroyModelMixin,                                    # 删除数据 
RetrieveModelMixin                                    # 单个数据获取

# 展示 添加 写在一起  
# 修改 删除 单个获取 写在一起

需要使用的序列化

from rest_framework import serializers
from .models import *

class CateSer(serializers.ModelSerializer):
class Meta:
model = Cate
fields = '__all__'

class BookSer(serializers.ModelSerializer):
pic = serializers.ImageField( use_url=False) # 用 mixin 展示图片需要
cate = serializers.SlugRelatedField(slug_field='name',read_only=True) # 获取分类的汉子
class Meta:
model = Book
fields = '__all__'

 添加和展示 view 写法

class CateView(GenericAPIView, ListModelMixin, CreateModelMixin):
    queryset = Cate.objects.all()
    serializer_class = CateSer

    def get(self, request):
        return self.list(request)                        # 展示

    def post(self, request):
        # response = self.create(request)
        return self.create(request)                        # 添加

单个获取和修改

class CateInfoView(GenericAPIView,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin):
    queryset = Cate.objects.all()
    serializer_class = CateSer

    def get(self,request,pk):
        return self.retrieve(request)                     # 单个获取

    def put(self,request,pk):
        return self.partial_update(request)             # 修改

    def delete(self,request,pk):
        return self.destroy(request)                    # 删除

mixin的url传参

from django.contrib import admin
from django.urls import path
from app01.views1 import *
from app01.views import *


urlpatterns = [
    path('admin/', admin.site.urls),
    path('cates', CateView.as_view()),                   # 添加和展示
    path('cates/<int:pk>/', CateInfoView.as_view()),    # 单个获取  修改  删除

    path('mybooks/',MyBookListView.as_view())            # 分页
]

mixin 的分页

#  mixin views  的写法
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin
from .ser import *
from .other import *

class MyBookListView(GenericAPIView,ListModelMixin):
    queryset = Book.objects.all()
    serializer_class = BookSer
    pagination_class = MyBookPage  

    def get(self,request):
        return self.list(request)
    
    
# 新建文件  other  里面写分页的方法

from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class MyBookPage(PageNumberPagination):
    page_size = 1                                                            # 默认第一页

    def get_paginated_response(self, data):
        # 这样子提供 : 提供上一页页码  下一页页码  当前页的总数  野马列表
        resp ={}
        resp['next_page'] = self.page.number + 1                               # 页数 + 1
        resp['prev_page'] = self.page.number - 1                            # 页数 - 1
        resp['num_list'] = [i for i in self.page.paginator.page_range]        # 遍历多少页
        resp['data'] = data                                                    # 获取的页面数据
        return Response(resp)

mixin 前端分页

<template>
    <div>
        <h1>图书列表</h1>
        <p v-for="book in page.data" :key="book.id">
            <a>{{book.name}}-{{book.price}}</a>
            <img :src="'/api/' + book.pic" style="width:350px;height:200px">
        </p>
        <div>
            <a @click="changepage(page.prev_page)">上一页</a>
            <a v-for="num in page.num_list" :key="num.id" @click="changepage(num)">{{num}}</a>
            <a @click="changepage(page.next_page)">下一页</a>
        </div>
    </div>
</template>

<script>
import axios from 'axios'
export default {
    data() {
        return {
            page:[],
            number:1
        }
    },
    created(){
        this.changepage(1)
    },methods:{
        changepage(num){
            axios.get('/api/mybooks/?page='+num).then(res=>{
                console.log(res.data)
                this.page = res.data
            })
        }
    }
}
</script>

<style>

</style>

图片详情配置

    # settion 配置
    
        MEDIA_URL = '/media/'

    # 图片配置
        MEDIA_ROOT = os.path.join(BASE_DIR,'uploads')
    
    
    # 一级url路由配置
        from django.urls import path,include,re_path
        from django.conf import settings
        from django.views.static import serve
        from django.conf.urls.static import static

re_path('^(?P<path>.*)/$',serve,{'document_root':settings.MEDIA_ROOT})

        if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,dpcument_root = settings.MEDIA_ROOT)

高级mixin方法 导包

# 导包
from rest_framework.generics import
    ListAPIView,         # 展示
    CreateAPIView,        # 添加
    UpdateAPIView,        # 修改
    RetrieveAPIView,    # 单个获取
    DestroyAPIView        # 删除
    
    
class CateView(CreateAPIView):   # 添加的高级操作
    serializer_class = 序列化

操作方法

class CateView(GenericAPIView,ListModelMixin,CreateModelMixin):
    queryset = CateModel
    serializer_class = CateSer

    def get(self,request):
        return self.list(request)
    
    def post(self,request):
        return self.create(request)

    def get_serializer_class(self):
        if self.request.method == 'GET':   # 获取分类表的数据
            return CateSer
        elif self.request.method == "POST": # 添加进标签表
            return TagSer

 



posted @ 2020-08-06 17:12  宋小凯  阅读(230)  评论(0编辑  收藏  举报