第十三单元 简化后端代码-增删改查

第十三单元 简化后端代码-增删改查,第1张

简化后端代码 简化前
# 学生
class  StudentsView(APIView):
    # 获取所有信息
    def get(self, request):
        stu_data = Students.objects.all()
        ser = StudentsSerializers2(instance=stu_data, many=True)
        return Response(ser.data, status=200)
    # 添加数据
    def post(self, request):
        ser = StudentsSerializers(data=request.data)
        if ser.is_valid(raise_exception=True):
            ser.save()
            return Response({'msg': 'succerr'}, status=201)
        return Response({'msg': 'error'}, status=400)
# 学生修改-删除
class StudentsView3(APIView):
    def put(self, request, id):
        try:
            stu_upd = Students.objects.get(id=id)
        except Exception as a:
            print(a)
            return Response({'msg': 'error'}, status=404)
        ser = StudentsSerializers(instance=stu_upd, data=request.data)
        if ser.is_valid(raise_exception=True):
            ser.save()
            return Response({"msg": 'succerr'}, status=201)
        return Response({'msg': 'error'}, status=400)

    # 删除学生信息
    def delete(self, request, id):
        try:
            del_data = Students.objects.filter(id=id).delete()
        except Exception as a:
            print(a)
            return Response({'msg': 'error'}, status=400)
        return Response({"msg": 'succerr'}, status=201)
用了扩展类后
# 查询学生信息
class StudentsView2(ListCreateAPIView):
    queryset = Students.objects.all()
    serializer_class = StudentsSerializers2
# 学生修改-删除
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
class StudentsView3(RetrieveUpdateDestroyAPIView):
    # 查询结果
    queryset = Students.objects.all()
    # 虚列化器
    serializer_class = StudentsSerializers
    # 过滤
    lookup_field = 'id'
    # 传参
    lookup_url_kwarg = 'id'

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/885851.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-14
下一篇 2022-05-14

发表评论

登录后才能评论

评论列表(0条)

保存