1
0

3 کامیت‌ها 15fba18513 ... 14a9879f78

نویسنده SHA1 پیام تاریخ
  DYaiu 14a9879f78 7-22作业第二步:job岗位的post和部门岗位中间表的crud 4 سال پیش
  DYaiu 18fbf1fc92 7-22作业第二步:树状dept的curd 4 سال پیش
  DYaiu 30b32acd5d 7-22作业第一步:建表(主表和表关联) 4 سال پیش
7فایلهای تغییر یافته به همراه251 افزوده شده و 5 حذف شده
  1. 2 1
      my_project/settings.py
  2. 2 1
      my_project/urls.py
  3. 73 0
      treeAndTable/migrations/0001_initial.py
  4. 54 1
      treeAndTable/models.py
  5. 10 0
      treeAndTable/serializer.py
  6. 13 0
      treeAndTable/urls.py
  7. 97 2
      treeAndTable/views.py

+ 2 - 1
my_project/settings.py

@@ -39,7 +39,8 @@ INSTALLED_APPS = [
     'django_filters',
     'workreport',
     'mptt',
-    'workTtree'
+    'workTtree',
+    'treeAndTable'
 ]
 
 MIDDLEWARE = [

+ 2 - 1
my_project/urls.py

@@ -20,5 +20,6 @@ from django.urls import path, include
 urlpatterns = [
     path('admin/', admin.site.urls),
     url(r'^', include('workreport.urls')),
-    url(r'^',include('workTtree.urls'))
+    url(r'^', include('workTtree.urls')),
+    url(r'^treeAndTable/', include('treeAndTable.urls'))
 ]

+ 73 - 0
treeAndTable/migrations/0001_initial.py

@@ -0,0 +1,73 @@
+# Generated by Django 3.0.8 on 2020-07-23 08:39
+
+from django.conf import settings
+from django.db import migrations, models
+import django.db.models.deletion
+import mptt.fields
+
+
+class Migration(migrations.Migration):
+
+    initial = True
+
+    dependencies = [
+        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='Department',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('name', models.CharField(max_length=20)),
+                ('lft', models.PositiveIntegerField(editable=False)),
+                ('rght', models.PositiveIntegerField(editable=False)),
+                ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)),
+                ('level', models.PositiveIntegerField(editable=False)),
+                ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='treeAndTable.Department')),
+            ],
+            options={
+                'verbose_name': '部门表',
+                'verbose_name_plural': '部门列表',
+            },
+        ),
+        migrations.CreateModel(
+            name='Job',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('name', models.CharField(max_length=20)),
+            ],
+            options={
+                'verbose_name': '岗位表',
+                'verbose_name_plural': '学校部门树形结构列表',
+            },
+        ),
+        migrations.CreateModel(
+            name='Dept_job',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('dept', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='treeAndTable.Department')),
+                ('job', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='treeAndTable.Job')),
+            ],
+            options={
+                'verbose_name': '部门岗位表',
+                'verbose_name_plural': '部门岗位关联表',
+                'db_table': 'dept_job',
+                'unique_together': {('dept', 'job')},
+            },
+        ),
+        migrations.CreateModel(
+            name='Dept_job_user',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('dept_job', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='treeAndTable.Dept_job')),
+                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
+            ],
+            options={
+                'verbose_name': '部门岗位关联人员表',
+                'verbose_name_plural': '部门岗位关联人员关联表',
+                'db_table': 'dept_job_user',
+                'unique_together': {('dept_job', 'user')},
+            },
+        ),
+    ]

+ 54 - 1
treeAndTable/models.py

@@ -1,3 +1,56 @@
+from django.contrib.auth.models import User
+from mptt.fields import TreeForeignKey
+from mptt.models import MPTTModel
 from django.db import models
 
-# Create your models here.
+
+# 岗位表
+class Job(models.Model):
+    name = models.CharField(max_length=20)
+
+    class Meta:
+        # db_table = 'job'
+        verbose_name = '岗位表'
+        verbose_name_plural = '学校部门树形结构列表'
+
+
+# 部门表
+class Department(MPTTModel):
+    name = models.CharField(max_length=20)
+    # 本表的树状
+    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)
+
+    class Meta:
+        # db_table = 'department'
+        verbose_name = '部门表'
+        verbose_name_plural = '部门列表'
+
+
+# 部门岗位中间表
+class Dept_job(models.Model):
+    # 部门外键
+    dept = models.ForeignKey('Department', on_delete=models.CASCADE)
+
+    # 岗位外键
+    job = models.ForeignKey('Job', on_delete=models.CASCADE)
+
+    class Meta:
+        db_table = 'dept_job'
+        verbose_name = '部门岗位表'
+        verbose_name_plural = '部门岗位关联表'
+        unique_together = ('dept', 'job')
+
+
+# 部门岗位中间表加人员的中间表
+class Dept_job_user(models.Model):
+    # 部门外键
+    dept_job = models.ForeignKey('Dept_job', on_delete=models.CASCADE)
+
+    # 人员外键
+    user = models.ForeignKey(User, on_delete=models.CASCADE)
+
+    class Meta:
+        db_table = 'dept_job_user'
+        verbose_name = '部门岗位关联人员表'
+        verbose_name_plural = '部门岗位关联人员关联表'
+        unique_together = ('dept_job', 'user')

+ 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__'

+ 13 - 0
treeAndTable/urls.py

@@ -0,0 +1,13 @@
+from django.conf.urls import url
+from rest_framework_bulk.routes import BulkRouter
+
+from treeAndTable.views import DepartmentView, DeptAndJobView
+
+router = BulkRouter()
+router.register(r'job', DeptAndJobView)
+
+urlpatterns = router.urls
+
+urlpatterns += [
+    url(r'^dept/', DepartmentView.as_view())
+]

+ 97 - 2
treeAndTable/views.py

@@ -1,3 +1,98 @@
-from django.shortcuts import render
+from django.db.models import F
+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
 
-# Create your views here.
+
+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)