views.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from django.db.models import F, ExpressionWrapper, BooleanField
  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').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 delete(self, request):
  33. try:
  34. # 当传递的id值不存在数据库或没有传id值直接捕获异常
  35. data = SchoolDept.objects.get(id=request.GET.get('id')).delete()
  36. except Exception:
  37. return Response(data={}, status=status.HTTP_400_BAD_REQUEST)
  38. return Response(data=data, status=status.HTTP_200_OK)