12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- from django.db.models import F
- from rest_framework import status
- from rest_framework.response import Response
- from rest_framework.views import APIView
- from workTtree.models import SchoolDept
- class SchoolDeptViews(APIView):
- def get(self, request):
- reqData = request.GET
- # 前端可以传0值也可没没有parent键
- parent = reqData.get('parent', '0')
- # 处理获取祖节点时数据库值为null的时候问题
- parentId = None if parent == '0' else parent
- if not parent.isdigit():
- return Response(data={}, status=status.HTTP_400_BAD_REQUEST)
- # annotate(has_childred=ExpressionWrapper(rl=1,output_field=BooleanField())).可以通过这个用sql生成避免for
- resData = SchoolDept.objects.filter(parent_id=parentId).annotate(childer=F('rght') - F('lft') - 1).values('id',
- 'name',
- 'remark',
- 'childer','parent_id').all()
- for res in resData:
- res['childer'] = res['childer'] // 2 != 0
- return Response(data=resData, status=status.HTTP_200_OK)
- def post(self, request):
- reqData = request.data
- # 获取前端给的父类id获取父类
- parent = SchoolDept.objects.get(id=reqData['id'])
- # 对象类型转换成dict类型
- data = SchoolDept.objects.create(name=reqData['name'], parent=parent).__dict__
- # 不删除该属性会转换json错误
- data.pop('_state')
- return Response(data=data, status=status.HTTP_200_OK)
- def put(self, request):
- data = request.data
- parent = SchoolDept.objects.get(id=data['id'])
- parent.name = data['name']
- parent.save()
- d = parent.__dict__
- d.pop('_state')
- return Response(data=d, status=status.HTTP_200_OK)
- def delete(self, request):
- try:
- # 当传递的id值不存在数据库或没有传id值直接捕获异常
- data = SchoolDept.objects.get(id=request.GET.get('id')).delete()
- except Exception:
- return Response(data={}, status=status.HTTP_400_BAD_REQUEST)
- return Response(data=data, status=status.HTTP_200_OK)
|