from django.db import IntegrityError from django.db.models import F from django.forms import model_to_dict from django.contrib.auth.models import User 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, Dept_job_user from treeAndTable.serializer import Dept_Job_Serializer, DeptJobUserSerializer 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) ''' 部门岗位中间表与user建立的中间表 ''' class DeptJobUserView(ModelViewSet): queryset = Dept_job_user.objects.all() serializer_class = DeptJobUserSerializer ''' 仅支持list类型的部门岗位id集 批量创建部门岗位的人员 ''' def create(self, request, *args, **kwargs): try: # 如果传入的部门必须包装成list deptJobId = request.data['dept_job_id'] if not isinstance(deptJobId, list): raise Exception name = request.data['name'] except Exception: return Response(data={'msg': '请求参数错误'}, status=status.HTTP_400_BAD_REQUEST) try: # 传入的用户名不能重复,如果没有当前用户就新建一个 user = User.objects.get(username=name) except Exception: user = User.objects.create_user(username=name, password='2020txts') # 批量创建 listinsert = list() for id in deptJobId: listinsert.append(Dept_job_user(dept_job_id=id, user_id=user.id)) try: Dept_job_user.objects.bulk_create(listinsert) except IntegrityError: return Response(data={'msg': '数据已经存在,不要添加重复数据'}, status=status.HTTP_400_BAD_REQUEST) return Response(data={'msg': 'success'}, status=status.HTTP_200_OK) ''' 返回的数据案例 [ { "id": 14, "user_id": 3, "user_name": "zangsan", "jobs": [ { "job_id": 4, "job_name": "测试岗位" }, { "job_id": 6, "user_name": "测试岗位1" } ] } ] 根据部门id获取部门下的所有人员和人员所分配到的岗位信息 ''' def list(self, request, *args, **kwargs): deptAndJob = Dept_job.objects.filter(dept_id=request.GET.get('dept_id', -1)).all().values() # 使用列表生成器生成该部门的所有岗位id数组查询所有人员 deptAndJobAndUser = Dept_job_user.objects.filter(dept_job_id__in=[DJ['id'] for DJ in deptAndJob]).all() # 返回前端的数据集 data = {} # 部门岗位人员中间表的数据集 for DJU in deptAndJobAndUser: # 如果该用户有多个岗位 if DJU.user.id in data: data[DJU.user.id]['jobs'].append({'job_id': DJU.dept_job.job.id, 'job_name': DJU.dept_job.job.name}) else: # 第一次包装用户的岗位信息 data[DJU.user.id] = { 'id': DJU.id, 'user_id': DJU.user.id, 'user_name': DJU.user.username, 'jobs': [ { 'job_id': DJU.dept_job.job.id, 'job_name': DJU.dept_job.job.name, } ] } # 前端table不接收有id的object,需转换成list data = [i for i in data.values()] return Response(data=data, status=status.HTTP_200_OK)