views.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from django.db.models import F
  2. from rest_framework import status
  3. from rest_framework.response import Response
  4. from rest_framework.views import APIView
  5. from workTtree.models import SchoolDept
  6. class SchoolDeptViews(APIView):
  7. def get(self, request):
  8. reqData = request.GET
  9. # 前端可以传0值也可没没有parent键
  10. parent = reqData.get('parent', '0')
  11. # 处理获取祖节点时数据库值为null的时候问题
  12. parentId = None if parent == '0' else parent
  13. if not parent.isdigit():
  14. return Response(data={}, status=status.HTTP_400_BAD_REQUEST)
  15. # annotate(has_childred=ExpressionWrapper(rl=1,output_field=BooleanField())).可以通过这个用sql生成避免for
  16. resData = SchoolDept.objects.filter(parent_id=parentId).annotate(childer=F('rght') - F('lft') - 1).values('id',
  17. 'name',
  18. 'remark',
  19. 'childer','parent_id').all()
  20. for res in resData:
  21. res['childer'] = res['childer'] // 2 != 0
  22. return Response(data=resData, status=status.HTTP_200_OK)
  23. def post(self, request):
  24. reqData = request.data
  25. # 获取前端给的父类id获取父类
  26. parent = SchoolDept.objects.get(id=reqData['id'])
  27. # 对象类型转换成dict类型
  28. data = SchoolDept.objects.create(name=reqData['name'], parent=parent).__dict__
  29. # 不删除该属性会转换json错误
  30. data.pop('_state')
  31. return Response(data=data, status=status.HTTP_200_OK)
  32. def put(self, request):
  33. data = request.data
  34. parent = SchoolDept.objects.get(id=data['id'])
  35. parent.name = data['name']
  36. parent.save()
  37. d = parent.__dict__
  38. d.pop('_state')
  39. return Response(data=d, status=status.HTTP_200_OK)
  40. def delete(self, request):
  41. try:
  42. # 当传递的id值不存在数据库或没有传id值直接捕获异常
  43. data = SchoolDept.objects.get(id=request.GET.get('id')).delete()
  44. except Exception:
  45. return Response(data={}, status=status.HTTP_400_BAD_REQUEST)
  46. return Response(data=data, status=status.HTTP_200_OK)