Browse Source

树练习的get接口实现

DYaiu 4 years ago
parent
commit
abc9ef79bc
3 changed files with 39 additions and 1 deletions
  1. 2 1
      my_project/urls.py
  2. 12 0
      workTtree/urls.py
  3. 25 0
      workTtree/views.py

+ 2 - 1
my_project/urls.py

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

+ 12 - 0
workTtree/urls.py

@@ -0,0 +1,12 @@
+from django.conf.urls import url
+from rest_framework_bulk.routes import BulkRouter
+
+from workTtree.views import SchoolDeptViews
+
+router = BulkRouter()
+
+urlpatterns = router.urls
+
+urlpatterns += [
+    url(r'^tree/', SchoolDeptViews.as_view())
+]

+ 25 - 0
workTtree/views.py

@@ -0,0 +1,25 @@
+from django.db.models import F, ExpressionWrapper, BooleanField
+from rest_framework import status
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from workTtree.models import SchoolDept
+
+
+class SchoolDeptViews(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)
+        # annotate(has_childred=ExpressionWrapper(rl=1,output_field=BooleanField())).可以通过这个用sql生成避免for
+        resData = SchoolDept.objects.filter(parent_id=parentId).annotate(childer=F('rght') - F('lft') - 1).values('id',
+                                                                                                                  'name',
+                                                                                                                  'remark',
+                                                                                                                  'childer').all()
+        for res in resData:
+            res['childer'] = res['childer'] // 2 != 0
+        return Response(data=resData, status=status.HTTP_200_OK)