def post(self, request, *args, **kwargs): # print(request.data) ser_obj = BookSerializer(data=request.data) if ser_obj.is_valid(): ser_obj.save() return Response(ser_obj.data) return Response(ser_obj.errors)
def put(self, request, pk, *args, **kwargs): obj = self.book_obj.get('obj') if not obj: return Response('更新数据不存在') ser_obj = BookSerializer(instance=obj, data=request.data, partial=True) if ser_obj.is_valid(): ser_obj.save() return Response(ser_obj.data) return Response(ser_obj.errors)
def post(self, request): ''' 提交数据添加一条书籍 :param request: :return: ''' print(request.data) serializer = BookSerializer(data=request.data, many=False) if serializer.is_valid(): serializer.save() # 保存到数据库中 create操作 return Response(serializer.data) else: return Response(serializer.errors)
def put(self, request, id): ''' 更新一条数据update :param request: :param id: :return: ''' edit_obj = Book.objects.get(pk=id) serializer = BookSerializer(data=request.data, instance=edit_obj) if serializer.is_valid(): serializer.save() # 返回更新后的数据 return Response(serializer.data) else: return Response(serializer.errors)
def get(self, request): ''' 查看多条数据 :param request: :return: ''' # print(request.user,request.auth) class MyPageNumberPagination(PageNumberPagination): page_size = 3 # 每页的显示的个数 page_query_param = "page_num" # 手动点击第几页 page_size_query_param = "size" # size手动是一页显示的个数 max_page_size = 5 # 最大的页显示的个数 book_list = Book.objects.get_queryset().order_by("nid") pnp = MyPageNumberPagination() paged_book_list = pnp.paginate_queryset(book_list, request) serializer = BookSerializer(paged_book_list, many=True) ''' 具体操作解析,就是怎么序列化的: serializer=BookSerializer(book_list,many=True) serializer.data: temp=[] for obj in book_list: temp.append({ "title":obj.title, "price":obj.price, "publish":obj.publish.email, if 字段SerializerMethodField: "authors":get_authors(obj) }) json.dumps(temp) ''' return Response(serializer.data)
def get(self, request, pk=None, *args, **kwargs): if not pk: all_book = models.Book.objects.all() else: all_book = models.Book.objects.filter(pk=pk) self.book_obj['obj'] = all_book.first() ser_obj = BookSerializer(all_book, many=True) # print(ser_obj.data, type(ser_obj.data)) return Response(ser_obj.data)
def get(self, request, id): ''' 查看一条数据 :param request: :param id: :return: ''' show_obj = Book.objects.get(pk=id) serializer = BookSerializer(show_obj, many=False) # 返回查看的单条数据 return Response(serializer.data)