Browse Source

增加部门,岗位,用户的CURD,连表查询

liceal 4 years ago
parent
commit
781849da77
51 changed files with 533 additions and 11 deletions
  1. BIN
      .README.md.swp
  2. 7 0
      .idea/dataSources.xml
  3. 1 0
      .idea/vcs.xml
  4. BIN
      Django_test/__pycache__/settings.cpython-37.pyc
  5. BIN
      Django_test/__pycache__/urls.cpython-37.pyc
  6. 11 6
      Django_test/settings.py
  7. 3 1
      Django_test/urls.py
  8. 1 0
      Pipfile
  9. 16 1
      Pipfile.lock
  10. 0 0
      even_table/__init__.py
  11. BIN
      even_table/__pycache__/__init__.cpython-37.pyc
  12. BIN
      even_table/__pycache__/admin.cpython-37.pyc
  13. BIN
      even_table/__pycache__/models.cpython-37.pyc
  14. BIN
      even_table/__pycache__/urls.cpython-37.pyc
  15. BIN
      even_table/__pycache__/views.cpython-37.pyc
  16. 3 0
      even_table/admin.py
  17. 5 0
      even_table/apps.py
  18. 56 0
      even_table/migrations/0001_initial.py
  19. 22 0
      even_table/migrations/0002_dept2jobs_user.py
  20. 29 0
      even_table/migrations/0003_auto_20200724_0853.py
  21. 31 0
      even_table/migrations/0004_auto_20200724_0918.py
  22. 0 0
      even_table/migrations/__init__.py
  23. BIN
      even_table/migrations/__pycache__/0001_initial.cpython-37.pyc
  24. BIN
      even_table/migrations/__pycache__/0002_dept2jobs_user.cpython-37.pyc
  25. BIN
      even_table/migrations/__pycache__/0003_auto_20200724_0853.cpython-37.pyc
  26. BIN
      even_table/migrations/__pycache__/0004_auto_20200724_0918.cpython-37.pyc
  27. BIN
      even_table/migrations/__pycache__/__init__.cpython-37.pyc
  28. 32 0
      even_table/models.py
  29. 3 0
      even_table/tests.py
  30. 10 0
      even_table/urls.py
  31. 156 0
      even_table/views.py
  32. 0 0
      mptt_test/__init__.py
  33. BIN
      mptt_test/__pycache__/__init__.cpython-37.pyc
  34. BIN
      mptt_test/__pycache__/admin.cpython-37.pyc
  35. BIN
      mptt_test/__pycache__/models.cpython-37.pyc
  36. BIN
      mptt_test/__pycache__/urls.cpython-37.pyc
  37. BIN
      mptt_test/__pycache__/views.cpython-37.pyc
  38. 3 0
      mptt_test/admin.py
  39. 5 0
      mptt_test/apps.py
  40. 31 0
      mptt_test/migrations/0001_initial.py
  41. 0 0
      mptt_test/migrations/__init__.py
  42. BIN
      mptt_test/migrations/__pycache__/0001_initial.cpython-37.pyc
  43. BIN
      mptt_test/migrations/__pycache__/__init__.cpython-37.pyc
  44. 15 0
      mptt_test/models.py
  45. 3 0
      mptt_test/tests.py
  46. 7 0
      mptt_test/urls.py
  47. 82 0
      mptt_test/views.py
  48. BIN
      workreport/__pycache__/models.cpython-37.pyc
  49. BIN
      workreport/__pycache__/urls.cpython-37.pyc
  50. 0 1
      workreport/models.py
  51. 1 2
      workreport/urls.py

BIN
.README.md.swp


+ 7 - 0
.idea/dataSources.xml

@@ -7,5 +7,12 @@
       <jdbc-driver>org.sqlite.JDBC</jdbc-driver>
       <jdbc-url>jdbc:sqlite:F:\txts\Django_test\test_django</jdbc-url>
     </data-source>
+    <data-source source="LOCAL" name="Django远程" uuid="42ba81ab-ccee-4adf-b0ff-3458b82a1fce">
+      <driver-ref>mysql.8</driver-ref>
+      <synchronize>true</synchronize>
+      <remarks>Django</remarks>
+      <jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver>
+      <jdbc-url>jdbc:mysql://srv.test.linkerplus.com:3310/linxa_django_demo</jdbc-url>
+    </data-source>
   </component>
 </project>

+ 1 - 0
.idea/vcs.xml

@@ -2,5 +2,6 @@
 <project version="4">
   <component name="VcsDirectoryMappings">
     <mapping directory="$PROJECT_DIR$/.." vcs="Git" />
+    <mapping directory="$PROJECT_DIR$" vcs="Git" />
   </component>
 </project>

BIN
Django_test/__pycache__/settings.cpython-37.pyc


BIN
Django_test/__pycache__/urls.cpython-37.pyc


+ 11 - 6
Django_test/settings.py

@@ -36,7 +36,10 @@ INSTALLED_APPS = [
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'rest_framework',
-    'workreport'
+    'workreport',
+    'mptt',
+    'mptt_test',
+    'even_table'
 ]
 
 MIDDLEWARE = [
@@ -80,7 +83,8 @@ DATABASES = {
         'NAME': 'linxa_django_demo',
         'USER': 'root',
         'PASSWORD': 'abc.123',
-        'HOST': 'srv.test.linkerplus.com',
+        # srv.test.linkerplus.com
+        'HOST': 'www.test.linkerplus.com',
         'PORT': '3310',
         'OPTIONS': {
             'init_command': 'SET sql_mode="STRICT_TRANS_TABLES"',
@@ -131,12 +135,13 @@ REST_FRAMEWORK = {
         'rest_framework.authentication.SessionAuthentication',
         'django.contrib.auth.backends.ModelBackend',
     ),
+    # PageNumberPagination 使用page传参分页
     'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
-    'PAGE_SIZE': 3,
+    'PAGE_SIZE': 5,
     'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
-    # 'DEFAULT_PERMISSION_CLASSES': [
-    #     'rest_framework.permissions.IsAuthenticated',
-    # ]
+    'DEFAULT_PERMISSION_CLASSES': [
+        'rest_framework.permissions.IsAuthenticated',
+    ]
 }
 
 AUTHENTICATION_BACKENDS = [

+ 3 - 1
Django_test/urls.py

@@ -22,5 +22,7 @@ from django.urls import path, include
 urlpatterns = [
     path('admin/', admin.site.urls),
     url(r'^api-auth/', include('rest_framework.urls')),
-    url(r'work/', include('workreport.urls'))  # 使用workreport工作区的路由
+    url(r'work/', include('workreport.urls')),  # 使用workreport工作区的路由
+    url(r'work/', include('mptt_test.urls')),  # 使用mptt
+    url(r'work/', include('even_table.urls')),
 ]

+ 1 - 0
Pipfile

@@ -11,6 +11,7 @@ djangorestframework = "*"
 djangorestframework-bulk = "*"
 django-filters = "*"
 django-filter = "*"
+django-mptt = "*"
 
 [requires]
 python_version = "3.7"

+ 16 - 1
Pipfile.lock

@@ -1,7 +1,7 @@
 {
     "_meta": {
         "hash": {
-            "sha256": "a35e0523a27ca548a7f655a88207bf5f79832e6386522b2a8689c84d08e1a114"
+            "sha256": "e0b5e0f679a5503eea904a68c5d9b798997e459784d00ad6e41a2835413b0d94"
         },
         "pipfile-spec": 6,
         "requires": {
@@ -47,6 +47,21 @@
             "index": "pypi",
             "version": "==0.2.1"
         },
+        "django-js-asset": {
+            "hashes": [
+                "sha256:8ec12017f26eec524cab436c64ae73033368a372970af4cf42d9354fcb166bdd",
+                "sha256:c163ae80d2e0b22d8fb598047cd0dcef31f81830e127cfecae278ad574167260"
+            ],
+            "version": "==1.2.2"
+        },
+        "django-mptt": {
+            "hashes": [
+                "sha256:90eb236eb4f1a92124bd7c37852bbe09c0d21158477cc237556d59842a91c509",
+                "sha256:dfdb3af75ad27cdd4458b0544ec8574174f2b90f99bc2cafab6a15b4bc1895a8"
+            ],
+            "index": "pypi",
+            "version": "==0.11.0"
+        },
         "djangorestframework": {
             "hashes": [
                 "sha256:05809fc66e1c997fd9a32ea5730d9f4ba28b109b9da71fccfa5ff241201fd0a4",

+ 0 - 0
even_table/__init__.py


BIN
even_table/__pycache__/__init__.cpython-37.pyc


BIN
even_table/__pycache__/admin.cpython-37.pyc


BIN
even_table/__pycache__/models.cpython-37.pyc


BIN
even_table/__pycache__/urls.cpython-37.pyc


BIN
even_table/__pycache__/views.cpython-37.pyc


+ 3 - 0
even_table/admin.py

@@ -0,0 +1,3 @@
+from django.contrib import admin
+
+# Register your models here.

+ 5 - 0
even_table/apps.py

@@ -0,0 +1,5 @@
+from django.apps import AppConfig
+
+
+class EvenTableConfig(AppConfig):
+    name = 'even_table'

+ 56 - 0
even_table/migrations/0001_initial.py

@@ -0,0 +1,56 @@
+# Generated by Django 3.0.8 on 2020-07-23 08:23
+
+from django.db import migrations, models
+import django.db.models.deletion
+import mptt.fields
+
+
+class Migration(migrations.Migration):
+
+    initial = True
+
+    dependencies = [
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='Dept',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('name', models.CharField(max_length=50)),
+                ('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, related_name='children', to='even_table.Dept')),
+            ],
+            options={
+                'verbose_name': '部门表',
+            },
+        ),
+        migrations.CreateModel(
+            name='Jobs',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('name', models.CharField(max_length=50)),
+            ],
+            options={
+                'verbose_name': '岗位表',
+            },
+        ),
+        migrations.CreateModel(
+            name='Dept2Jobs',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('lft', models.PositiveIntegerField(editable=False)),
+                ('rght', models.PositiveIntegerField(editable=False)),
+                ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)),
+                ('level', models.PositiveIntegerField(editable=False)),
+                ('dept', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='even_table.Dept')),
+                ('job', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='even_table.Jobs')),
+            ],
+            options={
+                'verbose_name': '部门岗位关联表',
+            },
+        ),
+    ]

+ 22 - 0
even_table/migrations/0002_dept2jobs_user.py

@@ -0,0 +1,22 @@
+# Generated by Django 3.0.8 on 2020-07-23 09:07
+
+from django.conf import settings
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+        ('even_table', '0001_initial'),
+    ]
+
+    operations = [
+        migrations.AddField(
+            model_name='dept2jobs',
+            name='user',
+            field=models.ForeignKey(blank=True, default=None, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
+            preserve_default=False,
+        ),
+    ]

+ 29 - 0
even_table/migrations/0003_auto_20200724_0853.py

@@ -0,0 +1,29 @@
+# Generated by Django 3.0.8 on 2020-07-24 00:53
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('even_table', '0002_dept2jobs_user'),
+    ]
+
+    operations = [
+        migrations.RemoveField(
+            model_name='dept2jobs',
+            name='level',
+        ),
+        migrations.RemoveField(
+            model_name='dept2jobs',
+            name='lft',
+        ),
+        migrations.RemoveField(
+            model_name='dept2jobs',
+            name='rght',
+        ),
+        migrations.RemoveField(
+            model_name='dept2jobs',
+            name='tree_id',
+        ),
+    ]

+ 31 - 0
even_table/migrations/0004_auto_20200724_0918.py

@@ -0,0 +1,31 @@
+# Generated by Django 3.0.8 on 2020-07-24 01:18
+
+from django.conf import settings
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+        ('even_table', '0003_auto_20200724_0853'),
+    ]
+
+    operations = [
+        migrations.AlterField(
+            model_name='dept2jobs',
+            name='dept',
+            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='even_table.Dept'),
+        ),
+        migrations.AlterField(
+            model_name='dept2jobs',
+            name='job',
+            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='even_table.Jobs'),
+        ),
+        migrations.AlterField(
+            model_name='dept2jobs',
+            name='user',
+            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
+        ),
+    ]

+ 0 - 0
even_table/migrations/__init__.py


BIN
even_table/migrations/__pycache__/0001_initial.cpython-37.pyc


BIN
even_table/migrations/__pycache__/0002_dept2jobs_user.cpython-37.pyc


BIN
even_table/migrations/__pycache__/0003_auto_20200724_0853.cpython-37.pyc


BIN
even_table/migrations/__pycache__/0004_auto_20200724_0918.cpython-37.pyc


BIN
even_table/migrations/__pycache__/__init__.cpython-37.pyc


+ 32 - 0
even_table/models.py

@@ -0,0 +1,32 @@
+from django.contrib.auth.models import User
+from django.db import models
+from mptt.fields import TreeForeignKey
+from mptt.models import MPTTModel
+
+
+# 部门表
+class Dept(MPTTModel):
+    name = models.CharField(max_length=50)
+    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
+
+    class Meta:
+        verbose_name = '部门表'
+
+
+# 岗位表
+class Jobs(models.Model):
+    name = models.CharField(max_length=50)
+
+    class Meta:
+        verbose_name = '岗位表'
+
+
+# 部门表 2 岗位表 关联表
+class Dept2Jobs(models.Model):
+    # 得到指定model的外键,会拿主键当外键,比如id,然后会在数据库生成字段后+ '_id'
+    dept = models.ForeignKey('Dept', on_delete=models.CASCADE, blank=True, null=True)
+    job = models.ForeignKey('Jobs', on_delete=models.CASCADE, blank=True, null=True)
+    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
+
+    class Meta:
+        verbose_name = '部门岗位关联表'

+ 3 - 0
even_table/tests.py

@@ -0,0 +1,3 @@
+from django.test import TestCase
+
+# Create your tests here.

+ 10 - 0
even_table/urls.py

@@ -0,0 +1,10 @@
+from django.conf.urls import url
+
+from even_table.views import deptView, jobsView, userView
+
+urlpatterns = []
+urlpatterns += [
+    url(r'dept/', deptView.as_view()),
+    url(r'jobs/', jobsView.as_view()),
+    url(r'user/', userView.as_view())
+]

+ 156 - 0
even_table/views.py

@@ -0,0 +1,156 @@
+import json
+
+from django.contrib.auth.models import User
+from django.db.models import Q
+from django.forms.models import model_to_dict
+from rest_framework import status
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from even_table.models import Dept, Jobs, Dept2Jobs
+
+
+# Create your views here.
+# 部门增删查改
+class deptView(APIView):
+    """
+    request {name名字},parent_id{父级id,可空}
+    创建一个节点
+    """
+
+    def post(self, request):
+        data = request.data
+        res = []
+        if 'parent_id' in data:
+            # try:
+            # 创建部门表,返回创建数据成功
+            # print(data['parent_id'])
+            # print(model_to_dict(Dept.objects.get(id=data['parent_id'])))
+            res = Dept.objects.create(
+                name=data['name'],
+                parent_id=data['parent_id']
+            )
+            res = model_to_dict(res)
+            res = {'node': res, 'message': data['name'] + ' 新增叶子成功'}
+            return Response(data=res, status=status.HTTP_200_OK)
+        # except Exception:
+        #     print(json.dump(Exception))
+        #     return Response(data={"message": '错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+
+        else:
+            # try:
+            res = Dept.objects.create(
+                name=data['name'],
+            )
+            res = model_to_dict(res)
+            res = {'node': res, 'message': data['name'] + ' 新增父级成功'}
+            return Response(data=res, status=status.HTTP_200_OK)
+        # except Exception:
+        #     return Response(data={"message": '错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+
+    """
+    得到节点
+    request{parent_id(节点id,可空)}
+    """
+
+    def get(self, request):
+        data = request.GET
+        res = []
+        if 'parent_id' in data:
+            # 给parent_id 拿到子集
+            res = Dept.objects.filter(parent_id=data['parent_id']).values().all()
+        else:
+            # 没有传name 则给第0层
+            res = Dept.objects.filter(parent_id=None).values().all()
+        return Response(data=res, status=status.HTTP_200_OK)
+
+    """
+    删除节点
+    {id:节点id}
+    """
+
+    def delete(self, request):
+        data = request.data
+        # 部门 删除这个部门
+        res = Dept.objects.filter(id=data['id']).delete()
+
+        # 岗位 删除这个部门下面的所有岗位
+        # Jobs.objects.filter()
+        # Dept2Jobs.objects.filter(dept_id=data['id'])
+
+        # 关联表 删除跟这个部门关联的
+        Dept2Jobs.objects.filter(dept_id=data['id']).delete()
+
+        return Response(data="删除成功", status=status.HTTP_200_OK)
+
+    """
+    更新节点
+    {id:节点id,name:节点名字,parent_id:父节点id(可空)}
+    """
+
+    def put(self, request):
+        data = request.data
+        if 'parent_id' in data:
+            res = Dept.objects.filter(id=data['id']).update(name=data['name'], parent_id=data['parent_id'])
+        else:
+            res = Dept.objects.filter(id=data['id']).update(name=data['name'])
+
+        return Response(data=res, status=status.HTTP_200_OK)
+
+
+# 岗位增删查改
+class jobsView(APIView):
+    # 增 {name:岗位名字,dept_id:父级部门id}
+    def post(self, request):
+        data = request.data
+        # 创建岗位
+        res = Jobs.objects.create(
+            name=data['name']
+        )
+        res = model_to_dict(res)
+        if res:
+            # 创建关联
+            Dept2Jobs.objects.create(
+                dept_id=data['dept_id'],
+                job_id=res['id']
+            )
+
+        return Response(data={'result': res, 'message': '创建岗位成功'}, status=status.HTTP_200_OK)
+
+    # 查 {dept_id:父级部门id(可空,空则查全部)}
+    def get(self, request):
+        # 从关联表里 查到 这个父级的id下的所有岗位id 查到job下面的所有name
+        names = Dept2Jobs.objects.filter(dept=request.GET['dept_id']).values("job", "job__name")
+        # print(ids)
+        return Response(data={'result': names, 'message': '查询成功'}, status=status.HTTP_200_OK)
+
+    # 更新 {id:岗位id,name:岗位新名字}
+    def put(self, request):
+        pass
+
+    # 删 {id:岗位id}
+    def delete(self, request):
+        # 删除关联表数据
+        data = request.data
+        Dept2Jobs.objects.filter(job_id=data['id']).delete()
+        # 删除岗位
+        Jobs.objects.filter(id=data['id']).delete()
+        return Response(data={'message': data['id'] + '删除成功'}, status=status.HTTP_200_OK)
+
+
+# 用户增删查改
+class userView(APIView):
+    def post(self, request):
+        pass
+
+    # 用户查询
+    def get(self, request):
+        data = request.GET
+        res = User.objects.values('id', 'username', 'email')
+        return Response(data={'result': res, 'message': '查询所有用户基础数据'}, status=status.HTTP_200_OK)
+
+    def put(self, request):
+        pass
+
+    def delete(self, request):
+        pass

+ 0 - 0
mptt_test/__init__.py


BIN
mptt_test/__pycache__/__init__.cpython-37.pyc


BIN
mptt_test/__pycache__/admin.cpython-37.pyc


BIN
mptt_test/__pycache__/models.cpython-37.pyc


BIN
mptt_test/__pycache__/urls.cpython-37.pyc


BIN
mptt_test/__pycache__/views.cpython-37.pyc


+ 3 - 0
mptt_test/admin.py

@@ -0,0 +1,3 @@
+from django.contrib import admin
+
+# Register your models here.

+ 5 - 0
mptt_test/apps.py

@@ -0,0 +1,5 @@
+from django.apps import AppConfig
+
+
+class MpttTestConfig(AppConfig):
+    name = 'mptt_test'

+ 31 - 0
mptt_test/migrations/0001_initial.py

@@ -0,0 +1,31 @@
+# Generated by Django 3.0.8 on 2020-07-21 06:42
+
+from django.db import migrations, models
+import django.db.models.deletion
+import mptt.fields
+
+
+class Migration(migrations.Migration):
+
+    initial = True
+
+    dependencies = [
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='Genre',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('name', models.CharField(max_length=50, unique=True)),
+                ('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, related_name='children', to='mptt_test.Genre')),
+            ],
+            options={
+                'abstract': False,
+            },
+        ),
+    ]

+ 0 - 0
mptt_test/migrations/__init__.py


BIN
mptt_test/migrations/__pycache__/0001_initial.cpython-37.pyc


BIN
mptt_test/migrations/__pycache__/__init__.cpython-37.pyc


+ 15 - 0
mptt_test/models.py

@@ -0,0 +1,15 @@
+from django.contrib.auth.models import User
+from django.db import models
+from django.db.models import Model
+from mptt.models import MPTTModel, TreeForeignKey
+
+
+# Create your models here.
+class Genre(MPTTModel):
+    name = models.CharField(max_length=50, unique=True)
+    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
+
+    class MPTTMeta:
+        order_insertion_by = ['name']
+
+

+ 3 - 0
mptt_test/tests.py

@@ -0,0 +1,3 @@
+from django.test import TestCase
+
+# Create your tests here.

+ 7 - 0
mptt_test/urls.py

@@ -0,0 +1,7 @@
+from django.conf.urls import url
+from mptt_test.views import mpttView
+
+urlpatterns = []
+urlpatterns += [
+    url(r'tree/', mpttView.as_view()),
+]

+ 82 - 0
mptt_test/views.py

@@ -0,0 +1,82 @@
+import json
+
+from django.db import IntegrityError
+from django.shortcuts import render
+from rest_framework import status
+from rest_framework.response import Response
+from rest_framework.views import APIView
+from mptt_test.models import Genre  # 模型
+from django.forms.models import model_to_dict
+
+
+# Create your views here.
+# 插入
+class mpttView(APIView):
+    """
+    request {name名字},parent_id{父级id,可空}
+    创建一个节点
+    """
+
+    def post(self, request):
+        data = request.data
+        res = []
+        if 'parent_id' in data:
+            try:
+                res = Genre.objects.create(
+                    name=data['name'],
+                    parent=Genre.objects.get(id=data['parent_id'])
+                )
+                res = {'node': model_to_dict(res), 'message': data['name'] + ' 新增叶子成功'}
+                return Response(data=res, status=status.HTTP_200_OK)
+            except Exception:
+                return Response(data={"message": '错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+
+        else:
+            try:
+                res = Genre.objects.create(
+                    name=data['name'],
+                )
+                res = {'node': model_to_dict(res), 'message': data['name'] + ' 新增父级成功'}
+                return Response(data=res, status=status.HTTP_200_OK)
+            except Exception:
+                return Response(data={"message": '错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+
+    """
+    得到节点
+    request{parent_id(节点id,可空)}
+    """
+
+    def get(self, request):
+        data = request.GET
+        res = []
+        if 'parent_id' in data:
+            # 给parent_id 拿到子集
+            res = Genre.objects.filter(parent_id=data['parent_id']).values().all()
+        else:
+            # 没有传name 则给第0层
+            res = Genre.objects.filter(parent_id=None).values().all()
+        return Response(data=res, status=status.HTTP_200_OK)
+
+    """
+    删除节点
+    {id:节点id}
+    """
+
+    def delete(self, request):
+        data = request.data
+        res = Genre.objects.filter(id=data['id']).delete()
+        return Response(data="删除成功", status=status.HTTP_200_OK)
+
+    """
+    更新节点
+    {id:节点id,name:节点名字,parent_id:父节点id(可空)}
+    """
+
+    def put(self, request):
+        data = request.data
+        if 'parent_id' in data:
+            res = Genre.objects.filter(id=data['id']).update(name=data['name'], parent_id=data['parent_id'])
+        else:
+            res = Genre.objects.filter(id=data['id']).update(name=data['name'])
+
+        return Response(data=res, status=status.HTTP_200_OK)

BIN
workreport/__pycache__/models.cpython-37.pyc


BIN
workreport/__pycache__/urls.cpython-37.pyc


+ 0 - 1
workreport/models.py

@@ -1,7 +1,6 @@
 from django.contrib.auth.models import User
 from django.db import models
 
-
 # Create your models here.
 class DailyReport(models.Model):
     # 生成的所有字段

+ 1 - 2
workreport/urls.py

@@ -12,8 +12,7 @@ router.register(r'dailyreport1', DailyReportView)
 urlpatterns = router.urls
 
 urlpatterns += [
-    url(r'report/', ReportView.as_view()),
+    url(r'report/<int:name>/', ReportView.as_view()),
     url(r'login/', LoginView.as_view()),
     url(r'logout/', LogoutView.as_view())
-
 ]