def get(self, request): # 查询所有数据集 all_articles = Article.objects.all() # 对数据集进行序列化 数据集为多时用many=True serializer = ArticleModelSerializer(instance=all_articles, many=True) # 返回前端响应 return Response(serializer.data)
def retrieve(self, request, pk): # 查询模型数据 try: article = Article.objects.get(pk=pk) except article.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) # 创建序列化器 serializer = ArticleModelSerializer(article) # 响应数据 return Response(serializer.data, status=status.HTTP_200_OK)
def get(self, request, pk): # 查询单个数据集 try: article = Article.objects.get(pk=pk) except Article.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) # 对数据集进行序列化 数据集为多时用many=True 单个数据集不需要这个参数 serializer = ArticleModelSerializer(instance=article) # 返回前端响应 return Response(serializer.data, status=status.HTTP_200_OK)
def create(self, request): # 创建序列化器 serializer = ArticleModelSerializer(data=request.data) # 验证数据 serializer.is_valid(raise_exception=True) # 保存数据 serializer.save() # 响应数据 return Response(serializer.data, status=status.HTTP_201_CREATED)
def post(self, request): # 新增 # 1.获取前端传入的请求体数据 data = request.data # 2.创建序列化器进行反序列化 serializer = ArticleModelSerializer(data=data) # 3.电泳序列化器的.is_valid方法进行校验,并自动抛出异常信息 serializer.is_valid(raise_exception=True) # 4.调用序列化器的save方法进行执行create方法 serializer.save(author=request.user) # 5.响应 return Response(serializer.data, status=status.HTTP_201_CREATED)
def update(self, request, pk): # 查询数据库对象 try: article = Article.objects.get(pk=pk) except article.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) # 创建序列化器 serializer = ArticleModelSerializer(instance=article, data=request.data) # 校验数据 serializer.is_valid(raise_exception=True) # 保存数据 serializer.save() # 响应数据 return Response(serializer.data, status=status.HTTP_204_NO_CONTENT)
def put(self, request, pk): # 修改数据 # 1.查询pk对应的单个数据 try: article = Article.objects.get(pk=pk) except Article.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) # 获取前端传过来的数据 data = request.data # 2.创建序列化器 serializer = ArticleModelSerializer(instance=article, data=data) # 3.校验 不需要if判断 有异常直接抛出 serializer.is_valid(raise_exception=True) # 4.save serializer.save(author=request.user) # 5.响应 return Response(serializer.data, status=status.HTTP_204_NO_CONTENT)
def list(self, request): # 获取数据列表 articles = Article.objects.all() # 创建序列化器 serializer = ArticleModelSerializer(instance=articles, many=True) return Response(serializer.data, status=status.HTTP_200_OK)