Пример #1
0
 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)
Пример #2
0
 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)
Пример #3
0
 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)
Пример #4
0
 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)