Browse Source

DeptJobUserView的新增成功,postman测试正确

DYaiu 4 years ago
parent
commit
03e7832f69
1 changed files with 37 additions and 1 deletions
  1. 37 1
      treeAndTable/views.py

+ 37 - 1
treeAndTable/views.py

@@ -1,10 +1,12 @@
+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
+from treeAndTable.models import Department, Dept_job, Job, Dept_job_user
 from treeAndTable.serializer import Dept_Job_Serializer
 
 
@@ -119,6 +121,40 @@ class DeptAndJobView(ModelViewSet):
         return Response(data=data, status=status.HTTP_200_OK)
 
 
+'''
+部门岗位中间表与user建立的中间表
+'''
+
+
 class DeptJobUserView(ModelViewSet):
     queryset = Dept_job.objects.all()
     serializer_class = Dept_Job_Serializer
+
+    '''
+    仅支持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)