REST framework(视图与视图组件)
一、APIView的简单使用
一个简单的序列化器:
from rest_framework.exceptions import ValidationError class BookSerialize(serializers.ModelSerializer): class Meta: model = models.Author fields = '__all__' # 索取数据库定义的所有字段,一般不用所有字段 # 获取指定字段 # fields = ("id","name")
视图的数据创建:
is_valid()与save()方法:这里实例化对象都是序列化器产生,调用的都是序列化器的父类方法
# 视图层 from rest_framework.views import APIView
from rest_framework.response import Response
class Books(APIView): def post(self, request): # 添加一条数据 print( request.data ) response = {"status": 100, "msg": "插入成功"} try: book_ser = BookSerialize(data=request.data) if book_ser.is_valid(): # 数据校验,查看钩子源码入口 is_valid 进入 book_ser.save() # 修改数据库 response['data'] = book_ser.data else: response['msg'] = book_ser.errors # 错误信息 except Exception as e: response['msg'] = str(e) return Response(response)
二、APIView的常见使用方法
2.1 不需要指定PK的视图方法:
get请求:获取所有数据,many=True
post:创建一条新数据
put:更新全部记录
from app01.myserialize import BookSerialize from rest_framework.response import Response from rest_framework.views import APIView
class Books(APIView): # get请求 查所有 def get(self, request, *args, **kwargs): response = {"status": 100, "msg": "查看所有"} all_book = Book.objects.all() ser = BookSerialize(all_book, many=True) response["data"] = ser.data # 序列化以后的数据在data里 return Response(response) # post请求 添加数据 def post(self, request): response = {"status": 100, "msg": "插入成功"} try: book_ser = BookSerialize(data=request.data) if book_ser.is_valid(): book_ser.save() response['data'] = book_ser.data else: response['msg'] = book_ser.errors except Exception as e: response['msg'] = str(e) return Response(response)
2.2 需要指定PK值的某一条数据操作:
get:获取单条记录,many=False
patch:更新某一条记录数据
delete:删除某一条数据
from app01.myserialize import BookSerialize
from rest_framework.response import Response
from rest_framework.views import APIView
class BookView(APIView): # get请求 查看一条数据 def get(self, request, pk, *args, **kwargs): response = {"status": 100, "msg": "查看单条"} book = Book.objects.filter(nid=pk).first() ser = BookSerialize(book, many=False) response["data"] = ser.data # 序列化以后的数据在data里 return Response(response) # delete请求 删除数据 def delete(self, request, pk, *args, **kwargs): Book.objects.filter(nid=pk).delete() return Response("") # patch请求 更新数据 def put(self, request, pk): response = {"status": 100, "msg": "修改成功"} book_obj = Book.objects.filter(nid=pk).first() book_ser = BookSerialize(data=request.data, instance=book_obj) # 反序列化,指定要修改的数据库 if book_ser.is_valid(): book_ser.save() # 修改数据库( rest_framework封装了代码 ) response["data"] = book_ser.data else: response["error"] = book_ser.error_messages return Response(response)
三、分页与排序
request.query_params 中可以获取?param1=32¶m2=23形式的参数.
class SurveysApi(ModelViewSet): pass """ 获取一组数据需要什么? 1, model 2, 序列化器 """ queryset = models.Survey.objects.all() # 实例化一个自定义的序列化器 serializer_class = basic.SurveySerializer # 过滤器,循环for实例化filter_backends,在调用filter_queryset()方法实现过滤 # 每个filter_queryset()方法在各自的类中SearchFilter/OrderingFilter/CustomFilter filter_backends = (filters.SearchFilter, filters.OrderingFilter, CustomFilter,) # 配合 filters.SearchFilter 使用, 如果想支持更多的字段搜索, 添加字段名称即可 search_fields = ("grade__name",) # 配合 filters.OrderingFilter 使用, 如果想支持更多的字段排序, 添加字段名称即可 ordering_fields = ("grade__name",) # 分页器 # 定义分页器类 pagination_class = pagination.LimitOffsetPagination # 表字段 table_column = [ { "prop": "grade", "label": "问卷班级" }, { "prop": "times", "label": "第几次" }, ] # 重写父类的list方法 def list(self, request, *args, **kwargs): # self.get_queryset()获取queryset值 queryset = self.filter_queryset(self.get_queryset()) # 帮助实现分页的代码 page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) """ 'request': self.request, 'format': self.format_kwarg, 'view': self """ # 重写自定义get_paginated_response方法,实现自定义字段的排序 return self.get_paginated_response(serializer.data) # 无分页情况 serializer = self.get_serializer(queryset, many=True) return Response( { "code": 0, "data": { "table_column": self.table_column, "table_data": serializer.data } } ) # 分页器 # 重写自定义get_paginated_response方法,实现自定义字段的排序 def get_paginated_response(self, data): """ request.query_params 中可以获取?param1=32¶m2=23形式的参数. request.query_params 返回的数据类型为QueryDict """ # 从查询字符串中获取到ordering参数 ordering = self.request.query_params.get("ordering", "") reverse = False if ordering: # 降序 if ordering.startswith("-"): reverse = True ordering = ordering[1:] # 列表排序 data.sort(key=lambda item: item[ordering], reverse=reverse) return Response( { "code": 0, "data": { "table_column": self.table_column, "table_data": { "total": self.paginator.count, "data": data } } } )
四、数据的创建
request.data获取form表单数据
class SurveysDetailApi(RetrieveAPIView, CreateAPIView): """ RetrieveAPIView 获取一条数据 CreateAPIView 创建数据 """ queryset = models.Survey.objects.all() # 实例化一个自定义的详情页序列化器 serializer_class = basic.SurveyDetailSerializer # 请求调查表详情页 def get_serializer_class(self): if self.request.method == "GET": # 序列化器读取操作 return basic.SurveyDetailSerializer else: # 序列化器创建操作 return basic.SurveyCreateSerializer # 字段校验,创建调查表
# 重写CreateAPIView的方法 def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) # 这里时serializer是通过序列化器实例化的对象,所有调用的serializers.ModelSerializer的is_valid方法 if serializer.is_valid(): # 同理:这里调用serializers.ModelSerializer的save方法 data = serializer.save() return Response( { "code": 0, "data": data } ) else: return Response( { "code": 1, "errors": serializer.errors } )
https://www.cnblogs.com/WiseAdministrator/