|
@@ -1,3 +1,51 @@
|
|
|
-from django.shortcuts import render
|
|
|
+from django.db.models import F
|
|
|
+from rest_framework import status
|
|
|
+from rest_framework.response import Response
|
|
|
+from rest_framework.views import APIView
|
|
|
|
|
|
-# Create your views here.
|
|
|
+from treeAndTable.models import Department
|
|
|
+
|
|
|
+
|
|
|
+class DepartmentView(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)
|
|
|
+ resData = Department.objects.filter(parent_id=parentId).annotate(has_leaf=F('rght') - F('lft') - 1).values('id',
|
|
|
+ 'name',
|
|
|
+ 'has_leaf',
|
|
|
+ 'parent_id').all()
|
|
|
+ for res in resData:
|
|
|
+ res['has_leaf'] = res['has_leaf'] // 2 == 0
|
|
|
+ return Response(data=resData, status=status.HTTP_200_OK)
|
|
|
+
|
|
|
+ def post(self, request):
|
|
|
+ reqData = request.data
|
|
|
+ # 获取前端给的父类id获取父类
|
|
|
+ parent = Department.objects.get(id=reqData['id'])
|
|
|
+ # 对象类型转换成dict类型
|
|
|
+ data = Department.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 = Department.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 = Department.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)
|