views.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 treeAndTable.models import Department
  6. class DepartmentView(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. resData = Department.objects.filter(parent_id=parentId).annotate(has_leaf=F('rght') - F('lft') - 1).values('id',
  16. 'name',
  17. 'has_leaf',
  18. 'parent_id').all()
  19. for res in resData:
  20. res['has_leaf'] = res['has_leaf'] // 2 == 0
  21. return Response(data=resData, status=status.HTTP_200_OK)
  22. def post(self, request):
  23. reqData = request.data
  24. # 获取前端给的父类id获取父类
  25. parent = Department.objects.get(id=reqData['id'])
  26. # 对象类型转换成dict类型
  27. data = Department.objects.create(name=reqData['name'], parent=parent).__dict__
  28. # 不删除该属性会转换json错误
  29. data.pop('_state')
  30. return Response(data=data, status=status.HTTP_200_OK)
  31. def put(self, request):
  32. data = request.data
  33. parent = Department.objects.get(id=data['id'])
  34. parent.name = data['name']
  35. parent.save()
  36. d = parent.__dict__
  37. d.pop('_state')
  38. return Response(data=d, status=status.HTTP_200_OK)
  39. def delete(self, request):
  40. try:
  41. # 当传递的id值不存在数据库或没有传id值直接捕获异常
  42. data = Department.objects.get(id=request.GET.get('id')).delete()
  43. except Exception:
  44. return Response(data={}, status=status.HTTP_400_BAD_REQUEST)
  45. return Response(data=data, status=status.HTTP_200_OK)