django rest framework
1 设置版本信息
from rest_framework.versioning import URLPathVersioning
1.1 settings.py
全局设置版本信息
#全局设置版本信息 REST_FRAMEWORK={ 'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.URLPathVersioning', 'VERSION_PARAM':'version', 'DEFAULT_VERSION':'v1', 'ALLOWED_VERSIONS':['v1','v2'], 'PAGE_SIZE':1, }
1.2 day97luffcity/urls.py
在url中体现版本信息
from django.contrib import admin from django.urls import path,include,re_path from api import urls urlpatterns = [ path('admin/', admin.site.urls), path('api/<str:version>/',include('api.urls')), ]
1.3 views/course.py
在视图中查看版本信息
from rest_framework.views import APIView
from rest_framework.versioning import URLPathVersioning
class CoursesView(APIView): #设置版本信息 #versioning_class = URLPathVersioning def get(self,request,*args,**kwargs): res=BaseResponse() #查看版本信息 #print(request.version)
2 分页处理
from rest_framework.pagination import PageNumberPagination
2.1 settings.py
在全局设置中设置分页的信息
#全局设置版本信息 REST_FRAMEWORK={ 'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.URLPathVersioning', 'VERSION_PARAM':'version', 'DEFAULT_VERSION':'v1', 'ALLOWED_VERSIONS':['v1','v2'], 'PAGE_SIZE':1, }
2.2 view/course.py
在视图中查看版本信息
from django.shortcuts import HttpResponse from rest_framework.views import APIView from rest_framework.versioning import URLPathVersioning from rest_framework.response import Response from rest_framework.pagination import PageNumberPagination from api.serializers.course import CourseSerializer from api.serializers.course import CourseModelSerializer from api import models from api.utils.response import BaseResponse class CoursesView(APIView): #设置版本信息 #versioning_class = URLPathVersioning def get(self,request,*args,**kwargs): res=BaseResponse() #查看版本信息 #print(request.version) try: #方式一 course_set=models.Course.objects.all() # 分页的处理 page = PageNumberPagination() ser_page = page.paginate_queryset(course_set, request, self) #ser=CourseSerializer(instance=ser_page,many=True) ser = CourseModelSerializer(instance=ser_page,many=True) res.code=1000 res.data=ser.data except Exception as e: res.code=500 res.error='获取数据失败' return Response(res.dict)
3 序列化的使用
设置序列化为
from rest_framework import serializers
3.1 在app中创建 serializers 的python包
serializers/course.py 设置 model中数据的 一对多,一对一,普通字段,还有选择字段的 取值序列化的展示方式
from rest_framework import serializers from api import models class CourseSerializer(serializers.Serializer): id=serializers.IntegerField() name=serializers.CharField() class CourseModelSerializer(serializers.ModelSerializer): #(level_choices = ((0, '初级'), (1, '中级'), (2, '高级')) 这种实现方式 level_name=serializers.CharField(source='get_level_display') #一对一,一对多的实现方式 hours=serializers.CharField(source='coursedetail.hours') #多对多的实现方式 recommend_courses=serializers.SerializerMethodField() #serializers.ModelSerializer 的实现方式 class Meta: model=models.Course fields=['id','name','level_name','hours','recommend_courses'] #多对多 def get_recommend_courses(self,row): recommend_list=row.coursedetail.recommend_courses.all() return [{'id':item.id,'name':item.name} for item in recommend_list]
3.2 views/course.py
在视图中取的数据后交给序列化的对象去处理
from django.shortcuts import HttpResponse from rest_framework.views import APIView from rest_framework.versioning import URLPathVersioning from rest_framework.response import Response from rest_framework.pagination import PageNumberPagination from api.serializers.course import CourseSerializer from api.serializers.course import CourseModelSerializer from api import models from api.utils.response import BaseResponse class CoursesView(APIView): #设置版本信息 #versioning_class = URLPathVersioning def get(self,request,*args,**kwargs): res=BaseResponse() #查看版本信息 #print(request.version) try: #方式一 course_set=models.Course.objects.all() # 分页的处理 page = PageNumberPagination() ser_page = page.paginate_queryset(course_set, request, self) #ser=CourseSerializer(instance=ser_page,many=True) ser = CourseModelSerializer(instance=ser_page,many=True) res.code=1000 res.data=ser.data except Exception as e: res.code=500 res.error='获取数据失败' return Response(res.dict) class CourseDetailView(APIView): def get(self,request,pk,*args,**kwargs): course_set = models.Course.objects.filter(pk=pk).first() # course_set_2=models.Course.objects.get(pk=pk) # print(type(course_set),type(course_set_2)) ser=CourseModelSerializer(instance=course_set) return Response(ser.data)