def channel_list(request): ''' 채널리스트 API --- 전체 채널의 목록을 보여주는 API입니다. ''' youtuber_name = request.query_params.get('youtuber_name') if youtuber_name is not None: # 유튜버 검색 기능 paginator = PageNumberPagination() paginator.page_size = 10 channel_querysets = list( Channel.objects.prefetch_related('video', 'channelviews').filter( channel_name__icontains=youtuber_name).order_by( '-subscriber_num')) # 데이터 많을 시 페이지네이션 진행(페이지별로 데이터 끊기) result_page = paginator.paginate_queryset(channel_querysets, request) # 데이터 직렬화 serializer = ChannelListSerializer(result_page, many=True) result = serializer.data additional_data = [] for channel_queryset in channel_querysets: videos = channel_queryset.video.order_by('-upload_time') video_counts = len(videos) recent_videos = videos[:2] recent_video_url = [] for recent_video in recent_videos: recent_video_url.append(recent_video.thumbnail_url) max_views_count = list( channel_queryset.channelviews.order_by('-check_time')[:1]) try: max_views_count = max_views_count[0].view_count except: max_views_count = 0 try: popularity = round( max_views_count / channel_queryset.subscriber_num, 1) except: popularity = 0 additional_data.append({ 'video_counts': video_counts, 'recent_videos': recent_video_url, 'max_views_count': max_views_count, 'popularity': popularity }) for i in range(len(result)): result[i].update(additional_data[i]) return paginator.get_paginated_response(result) else: paginator = PageNumberPagination() paginator.page_size = 10 queryset = Channel.objects.all() result_page = paginator.paginate_queryset(queryset, request) serializer = ChannelListSerializer(result_page, many=True) return paginator.get_paginated_response(serializer.data)
def list(self, request, *args, **kwargs): paginator = PageNumberPagination() paginator.page_size = 12 if 'no_page' in self.request.query_params: paginator.page_size = self.queryset.count() queryset = self.queryset.model.query_objects.filter_by_query_params( request) queryset = queryset.order_by('-id') queryset = paginator.paginate_queryset(queryset, request) serializer = ProductCategorySerializer( queryset, many=True, context={'request': self.request}) custom_data = {'data': serializer.data} return paginator.get_paginated_response(custom_data)
def MyCoursesInTheSubject(request, pk): subject = Subject.objects.get(id=pk) student = StudentProfile.objects.get(user=request.user) enrollments = Enrollment.objects.filter(student=student, course__subject=subject) # courseids = [] # for e in enrollments: # if e.course.id not in courseids: # courseids.append(e.course.id) # courses = Course.objects.filter(id__in=courseids) # filterset = CourseFilter(request.GET,queryset=courses) # if filterset.is_valid(): # queryset = filterset.qs # paginator = PageNumberPagination() # paginator.page_size = 10 # result_page = paginator.paginate_queryset(queryset, request) # serializer = EnrolledCourseSerializer(result_page, many=True) # return paginator.get_paginated_response(serializer.data) filterset = EnrollCourseFilter(request.GET, queryset=enrollments) if filterset.is_valid(): queryset = filterset.qs paginator = PageNumberPagination() paginator.page_size = 10 result_page = paginator.paginate_queryset(queryset, request) serializer = MycoursesSerializer(result_page, many=True) return paginator.get_paginated_response(serializer.data)
def list_products(request): """ The products lists with info and date time """ try: paginator = PageNumberPagination() paginator.page = request.GET.get('page') or 1 paginator.page_size = 10 product_status = request.GET.get('status') or [1, 2] product_status = json.loads(product_status) search_term = request.GET.get('search') or "" products_objects = ProductInfo.objects.filter( (Q(status__in=product_status)) & (Q(name__icontains=search_term) | Q(sku__icontains=search_term) | Q(description__icontains=search_term))) result_page = paginator.paginate_queryset(products_objects, request) products = FetchProductsSerializer(result_page, many=True) return Response( { 'msg': 'Products information retrived successfully!', 'data': products.data }, status=status.HTTP_200_OK) except Exception as e: return Response({'msg': str(e)}, status=status.HTTP_400_BAD_REQUEST)
def chat_api_view(request): if request.method == "GET": # Set Pagination paginator = PageNumberPagination() paginator.page_size = 100 obj = Chat.objects.filter(roomid_id=1).order_by('datetime') for i in obj: i.time = i.datetime.time() if obj: result_page = paginator.paginate_queryset(obj, request) serializer = ChatSerializer(result_page, many=True) return paginator.get_paginated_response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND) else: return Response(status=status.HTTP_400_BAD_REQUEST) # data = {} # print(request.data) # serializer = DocumentSerializer(data=request.data) # if serializer.is_valid(): # data['response'] = "that was good" # else: # data['response'] = "your file has problem" # else: # return Response(status=status.HTTP_400_BAD_REQUEST) # pass # return Response(data={'respose':'ok'})
def get(self, request, format="JSON"): try: per_list = Permission.objects.filter() page = PageNumberPagination() # 生成分页器对象 page.page_size = 100 # 设置每页的条数 # page.page_query_param = 'page' # url中查询第几页的key默认为'page # page.page_size_query_param = 'limit' # url中这一页数据的条数的key, 默认为None page.max_page_size = 50 # 每页的最大数据条数 page_list = page.paginate_queryset(per_list, request, self) # 生成这一页的数据列表 # page_list. # 将这一页的数据列表序列化 # return Response(ret.data) # 返回查到的数据列表 ret = PowerSerializer(page_list, many=True) for data in ret.data: data['children'] = [] for data in ret.data: if data['parent']: for vdata in ret.data: if vdata['id'] == data['parent']: vdata['children'].append((data)) Per = [] for data in ret.data: if data['parent'] == None: Per.append(data) jsondata = {} jsondata['code'] = 20000 jsondata['total'] = page.page.paginator.count jsondata['items'] = Per return Response(jsondata) except: return Response({'code': 0, 'msg': '设备列表获取失败'})
def new_arrival_product_list(request, currency_id, lang): """ List the the products ordered from newest arrival to oldest in paginated view """ if request.method == 'GET': if not Currency.exists(currency_id): return Response(data={"message": "currency doesn't exist"}, status=status.HTTP_404_NOT_FOUND) paginator = PageNumberPagination() paginator.page_size = 10 # @TODO: fix duplicate products recent_products = Product.objects.raw(''' SELECT product.* FROM Products_Product product JOIN Orders_Purchase purchase ON product.id = purchase.product_id WHERE product.balance > 0 AND product.active = True ORDER BY purchase.id DESC; ''') result_page = paginator.paginate_queryset(recent_products, request) serializer = ProductSerializer(result_page, many=True, context={ 'lang': lang, 'curr': currency_id }) return paginator.get_paginated_response(serializer.data)
def task_detail_view(request, pk, *args, **kwargs): try: task = PostTask.objects.get(id=pk) if task.job_status == "Completed": return Response({"detail": "Not Found"}, status=404) proposal = task.proposals.all().select_related( 'user', 'user__profile').order_by('created_at') paginator = PageNumberPagination() paginator.page_size = 4 paginator_qs = paginator.paginate_queryset(proposal, request) proposal_serializer = ProposalSerializer(paginator_qs, many=True) serializer = TasksSerializer(task, many=False, context={"request": request}) context = { "task": serializer.data, "proposals": proposal_serializer.data, } return paginator.get_paginated_response(context) # return Response(proposals, status=200) except PostTask.DoesNotExist: return Response({"detail": "Not Found"}, status=404)
def get(self, request, format="JSON"): user = request.user try: dept_id = user.dept.id dept_arr = [] depts = Department.objects.all() getDept(dept_id, depts, dept_arr).append(dept_id) query_params = list(request.query_params.keys()) kwargs = {} if 'title' in query_params: kwargs['title__contains'] = request.query_params['title'] kwargs['dept_id__in'] = dept_arr print(dept_arr) type_list = Role.objects.filter(**kwargs) page = PageNumberPagination() # 生成分页器对象 page.page_size = 20 # 设置每页的条数 page.page_query_param = 'page' # url中查询第几页的key默认为'page page.page_size_query_param = 'limit' # url中这一页数据的条数的key, 默认为None # page.max_page_size = 5 # 每页的最大数据条数 page_list = page.paginate_queryset(type_list, request, self) # 生成这一页的数据列表 # page_list. # 将这一页的数据列表序列化 # return Response(ret.data) # 返回查到的数据列表 ret = Roleserializer(page_list, many=True) jsondata = {} jsondata['code'] = 20000 jsondata['total'] = page.page.paginator.count jsondata['items'] = ret.data return Response(jsondata) except: return Response({'code': 0, 'msg': '设备列表获取失败'})
def list(self, request): paginator = PageNumberPagination() paginator.page_size = 5 queryset = Goods.objects.all() result_page = paginator.paginate_queryset(queryset, request) serializer = GameItemSerializer(result_page, many=True) return paginator.get_paginated_response(serializer.data)
def search_person(request): """ This Endpoint is for searching contact details of a person based on their email id or name. We will paginate this for 10 items at a time. """ try: persons = None paginator = PageNumberPagination() paginator.page_size = 10 name = request.GET.get("name") email = request.GET.get("email") if name and email: persons = Person.objects.filter(name__icontains=name, email__email__icontains=email) elif name: persons = Person.objects.filter(name__icontains=name) elif email: persons = Person.objects.filter(email__email__icontains=email) else: persons = Person.objects.all() paginated_persons = paginator.paginate_queryset(persons, request) serializer = PersonDetailSerializer(paginated_persons, many=True) return Response(serializer.data, status=status.HTTP_200_OK) except: print(traceback.format_exc()) return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def list(self, request): queryset = Image.objects.all() paginator = PageNumberPagination() paginator.page_size = 100 page = paginator.paginate_queryset(queryset, request) serializer = ImageSerializer(page, many=True).data return Response({"results": serializer})
def get(self, request): username = request.query_params.get('username', '') page_num = request.query_params.get('page', 1) limit = request.query_params.get('limit', 10) if username == '': user_data = User.objects.all().values('id', 'last_login', 'is_superuser', 'username', 'email', 'date_joined', 'is_active', 'first_name') else: user_data = User.objects.filter( username__icontains=username).values('id', 'last_login', 'is_superuser', 'username', 'email', 'date_joined', 'is_active', 'first_name') page = PageNumberPagination() # 实例化一个分页器 page.page_size = limit page_users = page.paginate_queryset(user_data, request, view=self) # 进行分页查询 serializer = UserSerializer(page_users, many=True) # 对分页后的结果进行序列化处理 resp = {'code': 0, 'data': serializer.data, 'count': user_data.count()} return Response(resp)
def CategoryView(request, categoryId=None): try: if request.method == "GET": if categoryId: c = Category.objects.get(id=categoryId) serializer = CategoryFormSerializer(c) return Response(serializer.data, status=status.HTTP_200_OK) else: if request.query_params.get('limit'): paginator = PageNumberPagination() paginator.page_size = 10 m = MenuItem.objects.all().order_by('item_id') result_page = paginator.paginate_queryset(m, request) serializer = MenuItemSerializer(m, many=True) return paginator.get_paginated_response(serializer.data) else: c = Category.objects.all() serializer = CategoryFormSerializer(c, many=True) return Response(serializer.data, status=status.HTTP_200_OK) else: context = {} context['method'] = request.method return Response({'detail': context}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: context = {} context['details'] = str(e) return Response(context, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def get_items_by_filter(request): # items = Item.objects.all() psize = 10 data = request.GET if data.get('from_date', False) is not False: from_date_string = data['from_date'].replace('T', ' ') + ":00" to_date_string = data['to_date'].replace('T', ' ') + ":59" from_date = datetime.strptime(from_date_string, '%Y-%m-%d %H:%M:%S') to_date = datetime.strptime(to_date_string, '%Y-%m-%d %H:%M:%S') items = Item.objects.filter(published_date__range=(from_date, to_date)) ordered = sorted(items, key=lambda item: datetime.strptime( item.published_date, '%Y-%m-%d %H:%M:%S'), reverse=True) else: items = Item.objects.all() ordered = sorted(items, key=lambda item: datetime.strptime( item.published_date, '%Y-%m-%d %H:%M:%S'), reverse=True) if data.get('size', False) is not False: psize = data['size'] # print(psize) paginator = PageNumberPagination() paginator.page_size = psize result_page = paginator.paginate_queryset(ordered, request) item_ser = ItemReadSerializer(result_page, many=True) return paginator.get_paginated_response(item_ser.data)
def getIndexValues(request, *args, **kargs): serialized_rq = DashboardGetIndexValuesSerializer( data=request.query_params) serialized_rq.is_valid(raise_exception=True) service = DashboardManagerService(request) query_set = service.getIndexValues(serialized_rq.validated_data) if query_set: paginator = PageNumberPagination() paginator.page_size = 1000 new_query_set = [] for item in query_set['results']: new_query_set.append(item) try: context = paginator.paginate_queryset(new_query_set, request) paginated_context = paginator.get_paginated_response(context) serializer = NodeDimensionValueSerializer(context, many=True) # absolute_uri = request.build_absolute_uri() return Response({ 'next': paginated_context.data['next'], 'previous': paginated_context.data['previous'], 'count': paginated_context.data['count'], 'results': serializer.data, }) except Exception as ex: pass return Response(status=status.HTTP_204_NO_CONTENT)
def get(self, request, slug, formate=None): paginator = PageNumberPagination() paginator.page_size = 10 profile = get_object_or_404(UsersProfile, slug=slug) attachment = ActivityAttachment.objects.filter( auth_user=profile.auth_user, type='AUDIO') # retrieve hidden activity_hidden = ActivityControl.objects.filter( auth_user=request.user).filter( Q(is_hidden=True) | Q(is_reported=True)).values('activity_id') activity_data = Activity.objects.filter(pk__in=[activity.activity.pk for activity in attachment]) \ .exclude(pk__in=[activity_hidden]) if activity_data: result_page = paginator.paginate_queryset(activity_data, request) data = ActivitySerializer(instance=result_page, many=True, context={ 'request': request }).data return paginator.get_paginated_response(data) else: raise DataNotFoundException return Response(status=HTTP_500_INTERNAL_SERVER_ERROR)
def get_team_list(request, format=None): paginator = PageNumberPagination() paginator.page_size = 25 teams = Team.objects.filter(active=True).order_by('name') result_page = paginator.paginate_queryset(teams, request) serializer = TeamShortSerializer(result_page, many=True) return paginator.get_paginated_response(serializer.data)
def get(self, request, format=None): paginator = PageNumberPagination() paginator.page_size = 10 # retrieve hidden activity_hidden = ActivityControl.objects.filter( auth_user=request.user).filter( Q(is_hidden=True) | Q(is_reported=True)).values('activity_id') # TODO get connection posts Friends or Company friends = Friend.objects.friends(request.user) friends.append(request.user) # Get company post profile_session = ProfileSession(request) company = profile_session.get_company() if company: company = company[1] if company: print("is company") activity_data = Activity.objects.filter(company=company, blocked=False) \ .exclude(pk__in=[activity_hidden]).prefetch_related('activity_attachment') else: activity_data = Activity.objects.filter(auth_user__in=[user for user in friends], blocked=False) \ .exclude(pk__in=[activity_hidden]).prefetch_related('activity_attachment') if activity_data: result_page = paginator.paginate_queryset(activity_data, request) data = ActivitySerializer(instance=result_page, many=True, context={ 'request': request }).data return paginator.get_paginated_response(data) else: raise DataNotFoundException return Response(status=HTTP_500_INTERNAL_SERVER_ERROR)
def search_resultado_api_view(request): """ Vista para buscar y listar todas las ordenes o recepciones de acuerdo a un parametro de busqueda. """ param = request.GET.get('param', '') terminadas = request.GET.get('terminadas', '') pagination = PageNumberPagination() pagination.page_size = 10 querys = ( Q(orden__paciente__pnombre__icontains=param) | Q(orden__paciente__papellido__icontains=param) | Q(orden__paciente__cedula__icontains=param) | Q(orden__id__icontains=param) | Q(orden__institucion__razon__icontains=param) | Q(orden__empresa__razon__icontains=param) | Q(orden__empresa_cliente__icontains=param) ) # servicios = Laboratorio.objects.all().values_list('servicio_id', flat=True) ordenes = Recepcion.objects.filter(querys).select_related('orden').exclude(orden__anulada=True).order_by( 'orden__paciente__pnombre', 'orden__paciente__papellido') if terminadas: ordenes = ordenes.filter(estado=Recepcion.RESULTADO_EMITIDO) else: ordenes = ordenes.filter(estado=Recepcion.EN_CURSO) result_pagination = pagination.paginate_queryset(ordenes, request) serializer = RecepcionSerializer(result_pagination, many=True) return pagination.get_paginated_response(serializer.data)
def get_channel(request): chan = Channel.objects.all() paginator = PageNumberPagination() paginator.page_size = 1 result_page = paginator.paginate_queryset(chan, request) chan_ser = ChannelReadSerializer(result_page, many=True) return paginator.get_paginated_response(chan_ser.data)
def bank_details(request): if request.method == "POST": if request.data.get("ifsc"): """ Get bank details with IFSC Code """ banks = Bank.objects.filter(ifsc=request.data["ifsc"]) if banks.count(): serializer = BankSerializer(banks[0]) return Response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND) if request.data.get("name") and request.data.get("city"): """ Get list of banks with Bank name and City in input """ paginator = PageNumberPagination() paginator.page_size = 10 banks = Bank.objects.filter(bank_name=request.data["name"], city=request.data.get("city")) payload = paginator.paginate_queryset(banks, request) serializer = BankSerializer(payload, many=True) return paginator.get_paginated_response(serializer.data) else: return Response(status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
def get_post_diagnosis(request): #get all diagnosis if request.method == 'GET': paginator = PageNumberPagination() paginator.page_size = 20 diagnosis = DiagnosisCode.objects.get_queryset().order_by('id') result_page = paginator.paginate_queryset(diagnosis, request) serializer = DiagnosisCodeSerializer(result_page,many=True) return paginator.get_paginated_response(serializer.data) #insert a new record for a diagnosis elif request.method == 'POST': data = { 'category_code' : request.data.get('category_code'), 'diagnosis_code' : request.data.get('diagnosis_code'), 'full_code' : request.data.get('full_code'), 'abbreviated_description' : request.data.get('abbreviated_description'), 'full_description' : request.data.get('full_description'), 'category_title' : request.data.get('category_title') } serializer = DiagnosisCodeSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get_all_challenges(request, challenge_time): """ Returns the list of all challenges """ try: q_params = {'published': True} if challenge_time.lower() == "past": q_params['end_date__lt'] = timezone.now() elif challenge_time.lower() == "present": q_params['start_date__lt'] = timezone.now() q_params['end_date__gt'] = timezone.now() elif challenge_time.lower() == "future": q_params['start_date__gt'] = timezone.now() challenge = Challenge.objects.filter(**q_params) paginator = PageNumberPagination() paginator.page_size = settings.REST_FRAMEWORK['PAGE_SIZE'] result_page = paginator.paginate_queryset(challenge, request) serializer = ChallengeSerializer(result_page, many=True) response_data = serializer.data return paginator.get_paginated_response(response_data) except: response_data = {'error': 'Wrong url pattern!'} return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)
def get(self, request): # get a task filters = {"user": request.user} for key in request.GET: if key != "page": filters[key] = request.GET[key] try: print(filters) tasks = Task.objects.filter(**filters).order_by("due_on") paginator = PageNumberPagination() paginator.page_size = 15 result_page = paginator.paginate_queryset(tasks, request) serializer = TaskSerializer(result_page, many=True, context={"request": request}) return Response({ "current_page": request.GET['page'], "total_pages": math.ceil(len(tasks) / 15), "count": len(result_page), "data": serializer.data }) except KeyError: return Response(data={ "message": "Bad request. The allowed fields are given in this response. You can use standard Django Queryset filters", "allowed_fields": "created_at, desc, due_on, labels, name, status, subtasks, user, user_id, uuid" }, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, format=None): api = Api.objects.all() paginator = PageNumberPagination() paginator.page_size = 2 result_page = paginator.paginate_queryset(api, request) serializer = ApiSerializer(result_page, many=True) return paginator.get_paginated_response(serializer.data)
def search_for_group(self, request): if request.data.get('phrase'): phrase = request.data.get('phrase') groups = Group.objects.filter(name__contains=phrase) else: phrase = ' ' groups = Group.objects.all() if len(phrase) < 2: return Response( data={'message': 'You provided too short search phrase'}, status=status.HTTP_406_NOT_ACCEPTABLE) paginator = PageNumberPagination() paginator.page_size = 10 response_groups = GroupSerializer(groups, context={ 'host': request.get_host() }, many=True).data data = paginator.paginate_queryset(response_groups, request) if len(data) == 0: return Response(status=status.HTTP_406_NOT_ACCEPTABLE, data={'message': 'No groups were found'}) return paginator.get_paginated_response(data=data)
def get_paginated_queryset_response(qs, request): paginator = PageNumberPagination() paginator.page_size = 20 paginated_qs = paginator.paginate_queryset(qs, request) serializer = TweetSerializer(paginated_qs, many=True) return paginator.get_paginated_response( serializer.data) # Response( serializer.data, status=200)
def list(self, request): rows = 12 if request.query_params.has_key('rows'): rows = request.query_params.get('rows').strip() paginator = PageNumberPagination() paginator.page_size = rows sort_field = "-update_time" if request.query_params.has_key('sort'): sort_field = request.query_params.get('sort') queryset = Image.objects.all().order_by(sort_field) if request.query_params.has_key('imagefolder_id'): if request.query_params.get('imagefolder_id') == '-1': queryset = queryset elif request.query_params.get('imagefolder_id') == '-2': queryset = queryset.exclude(is_video=True) elif request.query_params.get('imagefolder_id') == '-3': queryset = queryset.filter(is_video=True) elif request.query_params.get('imagefolder_id') == '-4': queryset = queryset.filter(imagefolder_id__isnull=True) else: queryset = queryset.filter(imagefolder_id=request.query_params. get('imagefolder_id').strip()) result_page = paginator.paginate_queryset(queryset, request) serializer = ImageSerializer(result_page, many=True) return_result = paginator.get_paginated_response(serializer.data) if request.query_params.has_key('page'): return_result.data['page'] = request.query_params.get('page') else: return_result.data['page'] = 1 return return_result
def challenge_list(request, challenge_host_team_pk): try: challenge_host_team = ChallengeHostTeam.objects.get( pk=challenge_host_team_pk) except ChallengeHostTeam.DoesNotExist: response_data = {'error': 'ChallengeHostTeam does not exist'} return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE) if request.method == 'GET': challenge = Challenge.objects.filter(creator=challenge_host_team) paginator = PageNumberPagination() paginator.page_size = settings.REST_FRAMEWORK['PAGE_SIZE'] result_page = paginator.paginate_queryset(challenge, request) serializer = ChallengeSerializer(result_page, many=True) response_data = serializer.data return paginator.get_paginated_response(response_data) elif request.method == 'POST': serializer = ChallengeSerializer( data=request.data, context={'challenge_host_team': challenge_host_team}) if serializer.is_valid(): serializer.save() response_data = serializer.data return Response(response_data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def paginated_queryset(queryset, request): """ Return a paginated queryset. """ paginator = PageNumberPagination() paginator.page_size = settings.REST_FRAMEWORK['PAGE_SIZE'] result_page = paginator.paginate_queryset(queryset, request) return (paginator, result_page)
def diffs(request, doctype_name, dataset_name): queryset = TreeNode.objects.select_related( 'dataset', 'tree2_diffs' ).filter( dataset__doctype__name=doctype_name, dataset__name=dataset_name, tree2_diffs__isnull=False ) paginator = PageNumberPagination() paginator.page_size = 1 result_page = paginator.paginate_queryset(queryset, request) serializer = KeySerializer(result_page, many=True) return paginator.get_paginated_response(serializer.data)
def plans(self, request, pk, *args, **kwargs): batch = get_object_or_404(Batch, id=pk) plans = Internship.objects.filter(intern__batch=batch).prefetch_related( 'rotation_requests__requested_department__department__hospital', 'rotation_requests__requested_department__department__specialty', 'rotation_requests__response', 'rotation_requests__forward', 'rotations__department__specialty', 'rotations__department__hospital', 'intern__profile__user__freezes', 'intern__profile__user__freeze_requests__response', 'intern__profile__user__freeze_cancel_requests__response', 'intern__profile__user__leaves', 'intern__profile__user__leave_requests__response', 'intern__profile__user__leave_cancel_requests__response', 'intern__university', 'intern__batch', ).order_by( Lower('intern__profile__en_first_name'), Lower('intern__profile__en_father_name'), Lower('intern__profile__en_grandfather_name'), Lower('intern__profile__en_last_name'), ) filtered = InternshipFilter({'intern__profile__en_full_name': request.query_params.get('query')}, plans) paginator = PageNumberPagination() paginator.page_size = 10 page = paginator.paginate_queryset(filtered.qs, request) if page is not None: serialized = FullInternshipSerializer2(page, many=True) return paginator.get_paginated_response(serialized.data) serialized = FullInternshipSerializer2(filtered.qs, many=True) return Response(serialized.data)
def element_fancy_search(request, query): """ List all ancestors' pk of the first element found. """ queryset = TreeNode.objects.only('id') for param in query.split(): if '!' in param: p = param.split('!') if len(p) > 2: break queryset = queryset.filter( dataset__doctype__name=p[0], dataset__name=p[1] ) elif '@' in param: # Search specified element by attribute p = param.split('@') if len(p) > 2: continue if p[0] and p[1]: if '=' in p[1]: a = p[1].split('=') if len(a) > 2: continue if a[0] and a[1]: # 'e@a=v' Search specified element by attribute name and value queryset = queryset.filter( element__type__name=p[0], element__attributes__type__name=a[0], element__attributes__value=a[1] ) elif a[1]: # 'e@=v' Search specified element by attribute value queryset = queryset.filter( element__type__name=p[0], element__attributes__value=a[1] ) else: # 'e@a' Search specified element by attribute name queryset = queryset.filter( element__type__name=p[0], element__attributes__type__name=p[1], ) elif p[1]: # Search any element by attribute if '=' in p[1]: a = p[1].split('=') if len(a) > 2: continue if a[0] and a[1]: # '@a=v' Search any element by attribute name and value queryset = queryset.filter( element__attributes__type__name=a[0], element__attributes__value=a[1] ) elif a[1]: # '@=v' Search any element by attribute value queryset = queryset.filter( element__attributes__value=a[1] ) else: # '@a' Search any element by attribute name queryset = queryset.filter( element__attributes__type__name=p[1] ) else: # '@' Search any element with attribute queryset = queryset.filter( element__attributes__isnull=False ) else: # if '=' in p[1]: # 'e=t' Search element by content # else: # 'e' Search specified element by name queryset = queryset.filter( element__type__name=param ) paginator = PageNumberPagination() paginator.page_size = 1 result_page = paginator.paginate_queryset(queryset, request) serializer = KeySerializer(result_page, many=True) return paginator.get_paginated_response(serializer.data)