feat: base 提供查询子集数据方法

This commit is contained in:
caoqianming 2024-02-26 08:08:47 +08:00
parent a1ef065e8c
commit e7f8086f23
2 changed files with 25 additions and 11 deletions

View File

@ -2,22 +2,27 @@ from django.apps import apps
from django.db.models import Q
def get_child_queryset_u(checkQueryset, obj, hasParent=True):
def get_child_queryset_u(checkQueryset, hasParent=True):
'''
获取所有子集
查的范围checkQueryset
父obj
是否包含父默认True
'''
cls = type(obj)
cls = type(checkQueryset.model)
if hasattr(cls, 'parent'):
queryset = cls.objects.none()
if hasParent:
queryset = cls.objects.filter(pk=obj.id)
child_queryset = checkQueryset.filter(parent=obj)
queryset = checkQueryset
child_queryset = checkQueryset.filter(parent__in=queryset)
while child_queryset.exists():
queryset = queryset | child_queryset
child_queryset = checkQueryset.filter(parent__in=child_queryset)
return queryset
elif hasParent:
return checkQueryset
else:
return checkQueryset.none()
def get_child_queryset(name, pk, hasParent=True):

View File

@ -12,7 +12,7 @@ from apps.system.models import DataFilter, Dept, User
from apps.utils.errors import PKS_ERROR
from apps.utils.mixins import MyLoggingMixin, BulkCreateModelMixin, BulkUpdateModelMixin, BulkDestroyModelMixin
from apps.utils.permission import ALL_PERMS, RbacPermission, get_user_perms_map
from apps.utils.queryset import get_child_queryset2
from apps.utils.queryset import get_child_queryset2, get_child_queryset_u
from apps.utils.serializers import PkSerializer, ComplexSerializer
from rest_framework.throttling import UserRateThrottle
from drf_yasg.utils import swagger_auto_schema
@ -100,6 +100,15 @@ class CustomGenericViewSet(MyLoggingMixin, GenericViewSet):
queryset = queryset.select_related(*self.select_related_fields)
if self.prefetch_related_fields:
queryset = queryset.prefetch_related(*self.prefetch_related_fields)
# 查询出子集数据,请谨慎使用
has_children = self.request.query_params.get('has_children', 'no')
if has_children == 'hasparent':
queryset = get_child_queryset_u(queryset, True)
elif has_children == 'noparent':
queryset = get_child_queryset_u(queryset, False)
else:
pass
return queryset
def get_queryset(self):