from django.db.models import F from django.forms import model_to_dict from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from treeAndTable.models import Department, Dept_job, Job from treeAndTable.serializer import Dept_Job_Serializer 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) ''' post { "dept_id":"33", "name":"舍长" } delete 路由带上id Put { "dept":18, "job":6 } ''' class DeptAndJobView(ModelViewSet): queryset = Dept_job.objects.all() serializer_class = Dept_Job_Serializer ''' 需要传递部门id和岗位名称 ''' def create(self, request): ''' 判断参数是否正确 根据部门id和岗位名字创建对应岗位和对应的中间表数据 :param request: :return: ''' try: deptId = request.data['dept_id'] name = request.data['name'] except Exception: return Response(data={'msg': '请求参数错误'}, status=status.HTTP_400_BAD_REQUEST) try: # 如果给定的岗位名称不存在岗位表直接新建一个岗位 job = Job.objects.get(name=name) except Exception: job = Job.objects.create(name=name) # 创建对应的中间表数据库 Dept_job.objects.create(dept_id=deptId, job_id=job.id) return Response(data={'msg': 'success'}, status=status.HTTP_200_OK) ''' 根据部门id获取部门岗位中间表的该部门所有岗位信息 返回中间表id和岗位name ''' def list(self, request, *args, **kwargs): deptId = request.GET.get('dept_id') print(deptId) deptAndJob = Dept_job.objects.filter(dept_id=deptId).all() data = [] for DJ in deptAndJob: data.append({ 'id': DJ.id, 'name': DJ.job.name }) return Response(data=data, status=status.HTTP_200_OK) class DeptJobUserView(ModelViewSet): queryset = Dept_job.objects.all() serializer_class = Dept_Job_Serializer