Browse Source

7-22作业第二步:job岗位的post和部门岗位中间表的crud

DYaiu 4 years ago
parent
commit
14a9879f78
3 changed files with 61 additions and 3 deletions
  1. 10 0
      treeAndTable/serializer.py
  2. 2 1
      treeAndTable/urls.py
  3. 49 2
      treeAndTable/views.py

+ 10 - 0
treeAndTable/serializer.py

@@ -0,0 +1,10 @@
+from rest_framework import serializers
+
+from treeAndTable.models import Dept_job
+
+
+class Dept_Job_Serializer(serializers.ModelSerializer):
+    class Meta:
+        model = Dept_job
+        # 全部都包含的意思
+        fields = '__all__'

+ 2 - 1
treeAndTable/urls.py

@@ -1,9 +1,10 @@
 from django.conf.urls import url
 from rest_framework_bulk.routes import BulkRouter
 
-from treeAndTable.views import DepartmentView
+from treeAndTable.views import DepartmentView, DeptAndJobView
 
 router = BulkRouter()
+router.register(r'job', DeptAndJobView)
 
 urlpatterns = router.urls
 

+ 49 - 2
treeAndTable/views.py

@@ -2,8 +2,9 @@ from django.db.models import F
 from rest_framework import status
 from rest_framework.response import Response
 from rest_framework.views import APIView
-
-from treeAndTable.models import Department
+from rest_framework.viewsets import ModelViewSet
+from treeAndTable.models import Department, Dept_job, Job
+from treeAndTable.serializer import Dept_Job_Serializer
 
 
 class DepartmentView(APIView):
@@ -49,3 +50,49 @@ class DepartmentView(APIView):
         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)