views.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. from django.db import IntegrityError
  2. from django.db.models import F
  3. from django.forms import model_to_dict
  4. from django.contrib.auth.models import User
  5. from rest_framework import status
  6. from rest_framework.response import Response
  7. from rest_framework.views import APIView
  8. from rest_framework.viewsets import ModelViewSet
  9. from treeAndTable.models import Department, Dept_job, Job, Dept_job_user
  10. from treeAndTable.serializer import Dept_Job_Serializer, DeptJobUserSerializer
  11. class DepartmentView(APIView):
  12. def get(self, request):
  13. reqData = request.GET
  14. # 前端可以传0值也可没没有parent键
  15. parent = reqData.get('parent', '0')
  16. # 处理获取祖节点时数据库值为null的时候问题
  17. parentId = None if parent == '0' else parent
  18. if not parent.isdigit():
  19. return Response(data={}, status=status.HTTP_400_BAD_REQUEST)
  20. resData = Department.objects.filter(parent_id=parentId).annotate(has_leaf=F('rght') - F('lft') - 1).values('id',
  21. 'name',
  22. 'has_leaf',
  23. 'parent_id').all()
  24. for res in resData:
  25. res['has_leaf'] = res['has_leaf'] // 2 == 0
  26. return Response(data=resData, status=status.HTTP_200_OK)
  27. def post(self, request):
  28. reqData = request.data
  29. # 获取前端给的父类id获取父类
  30. parent = Department.objects.get(id=reqData['id'])
  31. # 对象类型转换成dict类型
  32. data = Department.objects.create(name=reqData['name'], parent=parent).__dict__
  33. # 不删除该属性会转换json错误
  34. data.pop('_state')
  35. return Response(data=data, status=status.HTTP_200_OK)
  36. def put(self, request):
  37. data = request.data
  38. parent = Department.objects.get(id=data['id'])
  39. parent.name = data['name']
  40. parent.save()
  41. d = parent.__dict__
  42. d.pop('_state')
  43. return Response(data=d, status=status.HTTP_200_OK)
  44. def delete(self, request):
  45. try:
  46. # 当传递的id值不存在数据库或没有传id值直接捕获异常
  47. data = Department.objects.get(id=request.GET.get('id')).delete()
  48. except Exception:
  49. return Response(data={}, status=status.HTTP_400_BAD_REQUEST)
  50. return Response(data=data, status=status.HTTP_200_OK)
  51. '''
  52. post
  53. {
  54. "dept_id":"33",
  55. "name":"舍长"
  56. }
  57. delete
  58. 路由带上id
  59. Put
  60. {
  61. "dept":18,
  62. "job":6
  63. }
  64. '''
  65. class DeptAndJobView(ModelViewSet):
  66. queryset = Dept_job.objects.all()
  67. serializer_class = Dept_Job_Serializer
  68. '''
  69. 需要传递部门id和岗位名称
  70. '''
  71. def create(self, request):
  72. '''
  73. 判断参数是否正确
  74. 根据部门id和岗位名字创建对应岗位和对应的中间表数据
  75. :param request:
  76. :return:
  77. '''
  78. try:
  79. deptId = request.data['dept_id']
  80. name = request.data['name']
  81. except Exception:
  82. return Response(data={'msg': '请求参数错误'}, status=status.HTTP_400_BAD_REQUEST)
  83. try:
  84. # 如果给定的岗位名称不存在岗位表直接新建一个岗位
  85. job = Job.objects.get(name=name)
  86. except Exception:
  87. job = Job.objects.create(name=name)
  88. # 创建对应的中间表数据库
  89. Dept_job.objects.create(dept_id=deptId, job_id=job.id)
  90. return Response(data={'msg': 'success'}, status=status.HTTP_200_OK)
  91. '''
  92. 根据部门id获取部门岗位中间表的该部门所有岗位信息
  93. 返回中间表id和岗位name
  94. '''
  95. def list(self, request, *args, **kwargs):
  96. deptId = request.GET.get('dept_id')
  97. print(deptId)
  98. deptAndJob = Dept_job.objects.filter(dept_id=deptId).all()
  99. data = []
  100. for DJ in deptAndJob:
  101. data.append({
  102. 'id': DJ.id,
  103. 'name': DJ.job.name
  104. })
  105. return Response(data=data, status=status.HTTP_200_OK)
  106. '''
  107. 部门岗位中间表与user建立的中间表
  108. '''
  109. class DeptJobUserView(ModelViewSet):
  110. queryset = Dept_job_user.objects.all()
  111. serializer_class = DeptJobUserSerializer
  112. '''
  113. 仅支持list类型的部门岗位id集
  114. 批量创建部门岗位的人员
  115. '''
  116. def create(self, request, *args, **kwargs):
  117. try:
  118. # 如果传入的部门必须包装成list
  119. deptJobId = request.data['dept_job_id']
  120. if not isinstance(deptJobId, list):
  121. raise Exception
  122. name = request.data['name']
  123. except Exception:
  124. return Response(data={'msg': '请求参数错误'}, status=status.HTTP_400_BAD_REQUEST)
  125. try:
  126. # 传入的用户名不能重复,如果没有当前用户就新建一个
  127. user = User.objects.get(username=name)
  128. except Exception:
  129. user = User.objects.create_user(username=name, password='2020txts')
  130. # 批量创建
  131. listinsert = list()
  132. for id in deptJobId:
  133. listinsert.append(Dept_job_user(dept_job_id=id, user_id=user.id))
  134. try:
  135. Dept_job_user.objects.bulk_create(listinsert)
  136. except IntegrityError:
  137. return Response(data={'msg': '数据已经存在,不要添加重复数据'}, status=status.HTTP_400_BAD_REQUEST)
  138. return Response(data={'msg': 'success'}, status=status.HTTP_200_OK)
  139. '''
  140. 返回的数据案例
  141. [
  142. {
  143. "id": 14,
  144. "user_id": 3,
  145. "user_name": "zangsan",
  146. "jobs": [
  147. {
  148. "job_id": 4,
  149. "job_name": "测试岗位"
  150. },
  151. {
  152. "job_id": 6,
  153. "user_name": "测试岗位1"
  154. }
  155. ]
  156. }
  157. ]
  158. 根据部门id获取部门下的所有人员和人员所分配到的岗位信息
  159. '''
  160. def list(self, request, *args, **kwargs):
  161. deptAndJob = Dept_job.objects.filter(dept_id=request.GET.get('dept_id', -1)).all().values()
  162. # 使用列表生成器生成该部门的所有岗位id数组查询所有人员
  163. deptAndJobAndUser = Dept_job_user.objects.filter(dept_job_id__in=[DJ['id'] for DJ in deptAndJob]).all()
  164. # 返回前端的数据集
  165. data = {}
  166. # 部门岗位人员中间表的数据集
  167. for DJU in deptAndJobAndUser:
  168. # 如果该用户有多个岗位
  169. if DJU.user.id in data:
  170. data[DJU.user.id]['jobs'].append({'job_id': DJU.dept_job.job.id, 'job_name': DJU.dept_job.job.name})
  171. else:
  172. # 第一次包装用户的岗位信息
  173. data[DJU.user.id] = {
  174. 'id': DJU.id,
  175. 'user_id': DJU.user.id,
  176. 'user_name': DJU.user.username,
  177. 'jobs': [
  178. {
  179. 'job_id': DJU.dept_job.job.id,
  180. 'job_name': DJU.dept_job.job.name,
  181. }
  182. ]
  183. }
  184. # 前端table不接收有id的object,需转换成list
  185. data = [i for i in data.values()]
  186. return Response(data=data, status=status.HTTP_200_OK)