Advertisement
Mochinov

Untitled

Apr 10th, 2023
815
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.27 KB | None | 0 0
  1.  
  2. class MasterDataElementFilterViewSet(ViewSetActionPermissionMixin, viewsets.ModelViewSet):
  3.     permission_classes = [permissions.IsAuthenticated]
  4.     pagination_class = CustomPageNumberPagination
  5.     serializer_class = MasterDataFilterSerializer
  6.  
  7.     def get_queryset(self):
  8.         active_project_id = self.request.user.active_project_id
  9.  
  10.         if not active_project_id:
  11.             raise UserHasNoActiveProjectSet(language_code=self.request.user.language.code)
  12.  
  13.         try:
  14.             parent_id = int(self.request.query_params.get('parent_id'))
  15.         except TypeError:
  16.             parent_id = None
  17.  
  18.         hierarchy = get_object_or_404(
  19.             MasterDataHierarchy.objects.all(),
  20.             id=self.kwargs.get('pk'),
  21.             project_id=active_project_id
  22.         )
  23.  
  24.         if parent_id:
  25.             return MasterDataElement.objects.filter(
  26.                 level__hierarchy_id=hierarchy.id,
  27.                 parent_id=parent_id,
  28.                 is_archived=False
  29.             ).annotate(Count('children', distinct=True))
  30.         else:
  31.  
  32.             try:
  33.                 statuses = loads(self.request.query_params.get('statuses', ''))
  34.             except JSONDecodeError:
  35.                 statuses = None
  36.  
  37.             last_hierarchy_level = MasterDataLevel.get_levels_in_hierarchical_order_for_hierarchy(hierarchy.id)
  38.  
  39.             logger = logging.getLogger(__name__)
  40.  
  41.             queryset = MasterDataElement.objects.filter(
  42.                 level__id=last_hierarchy_level.last().id,
  43.                 is_archived=False,
  44.                 level__hierarchy_id=hierarchy.id,
  45.             )
  46.  
  47.             if statuses:
  48.                 level_count = range(last_hierarchy_level.count()-1)
  49.                 field_query = '__'.join(['children' for _ in level_count]) + '__info__calculated_status_id'
  50.                 query_string = Q(**{field_query: statuses[0]})
  51.  
  52.                 for status in statuses[1:]:
  53.                     query_string.add(Q(**{field_query: status}), Q.OR)
  54.  
  55.                 queryset = queryset.filter(query_string)
  56.  
  57.             return queryset.select_related(
  58.                 'info__calculated_status',
  59.                 'info__manual_status',
  60.             ).annotate(
  61.                 Count('children', distinct=True)
  62.             ).order_by('-id')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement