def get(self, request, format=None): payment = Payment.objects.all().using('default').order_by( 'id') # TODO orderby something logical paginator = PageNumberPagination() paginator.max_page_size = 100 paginator.page_size_query_param = 'page_size' result_page = paginator.paginate_queryset(payment, request) serializer = PaymentSerializer(result_page, many=True, context={'request': request}) current_page = paginator.page.number total_pages = int(str(paginator.page).split(" ")[3].split(">")[0]) page_size = len(serializer.data) previous_page = str(paginator.get_previous_link()) next_page = str(paginator.get_next_link()) return JsonResponse(data={ 'page_size': page_size, 'results': serializer.data, 'next_page': next_page, 'previous_page': previous_page, 'current_page': current_page, 'total_pages': total_pages }, status=200, safe=False)
def search(request, query): """ Lista resultados de búsqueda de palabra clave. Usa paginación y muestra hasta 20 resultados por página. Además muestra links para páginas previas y siguientes. # Puedes obtener los resultados en archivo TSV Este archivo contiene la información en campos separados por tabs (fácil de importar a MS Excel) Solo es necesario usar la dirección `search.tsv`: * <http://manolo.rocks/api/search.tsv/romulo/> --- type: query: required: true type: string parameters: - name: query description: nombre o palabra clave a busar, por ejemplo Romulo type: string paramType: path required: true """ query_request = QueryDict('q={}'.format(query)) form = ApiForm(query_request) if request.user.is_authenticated(): all_items = form.search(premium=True) else: all_items = form.search(premium=False) pagination = PageNumberPagination() paginated_results = pagination.paginate_queryset(all_items, request) paginated_results = [i.object for i in paginated_results] serializer = ManoloSerializer(paginated_results, many=True) data = { 'count': pagination.page.paginator.count, 'next': pagination.get_next_link(), 'previous': pagination.get_previous_link(), 'results': serializer.data, } return JSONResponse(data)
def to_representation(self, instance): representation = super(BlogPostsSerializer, self).to_representation(instance) request = self.context.get('request') if request: paginator = PageNumberPagination() posts = paginator.paginate_queryset( instance.posts.filter(publish_date_lte=timezone.now()), request) serializer = BlogPostListSerializer(posts, many=True) representation['posts'] = OrderedDict([ ('count', paginator.page.paginator.count), ('next', paginator.get_next_link()), ('previous', paginator.get_previous_link()), ('results', serializer.data) ]) return representation
def list_articles(self, request, **kwargs): articles = Article.objects.filter( is_featured=False).order_by('-date_published') p = PageNumberPagination() page = p.paginate_queryset(articles, request) serializer = ArticleSerializer(page, many=True) results = { 'pagination': { 'has_prev': p.get_previous_link(), 'page': p.page.number, 'count': p.page.paginator.count, 'total_pages': p.page.paginator.num_pages, 'has_next': p.get_next_link() }, 'results': serializer.data } return Response(results, status=200)
def all_generes(request): """List all Genres.""" try: if request.method == 'GET': generes = Genere.objects.all() count = generes.count() '''Creating paginator''' paginator = PageNumberPagination() generes = paginator.paginate_queryset(generes, request) genere_list = [] for genere in generes: genere_list.append( OrderedDict([('id', genere.id), ('name', genere.genere)])) data = OrderedDict([('count', count), ('next', paginator.get_next_link()), ('previous', paginator.get_previous_link()), ('results', genere_list)]) return Response(data) except: print "========= all_generes() Expection =======" data = OrderedDict([('count', 0), ('next', None), ('previous', None), ('results', 'Genre Not Found')]) return Response(data) """Creating new Genre.""" try: data = {} if request.method == 'POST': load = request.data if load['name'] != '': Genere.objects.create(genere=load['name']) data = {'message': 'Genre Created'} else: data = { 'message': 'Genre Not Created, please add data in proper format.' } return Response(data) except: print "========= all_generes() Expection =======" data = OrderedDict([('count', 0), ('next', None), ('previous', None), ('results', 'Genre Not Created')]) return Response(data)
def get(self, request, *args, **kwargs): app_name, table_name = args model_admin = sites.site.enabled_admins[app_name][table_name] # auto_serializer=create_serializer(model_admin.model,model_admin.list_display) query_set = model_admin.model.objects.all() query_set, filter_condtions = table_filter(request, model_admin) query_set = table_search(request, model_admin, query_set) pg = PageNumberPagination() pg_set = pg.paginate_queryset(request=request, queryset=query_set, view=self) ser = self.serializer_class(instance=pg_set, many=True) print(pg.page.number) print(pg.get_next_link()) data = ser.data if data: fields = data[0].keys() return render(request, 'tables/table_detail.html', locals())
def all_tracks(request): """List all Tracks.""" try: if request.method == 'GET': tracks = Music.objects.all() count = tracks.count() '''Creating paginator''' paginator = PageNumberPagination() track_objs = paginator.paginate_queryset(tracks, request) track_list = [] for track in track_objs: genere_list = [] for i in track.genere.all(): genere_list.append( OrderedDict([('id', i.id), ('name', i.genere)])) track_list.append( OrderedDict([('id', track.id), ('title', track.title), ('rating', average(track.music_track.all())), ('genres', genere_list)])) data = OrderedDict([('count', count), ('next', paginator.get_next_link()), ('previous', paginator.get_previous_link()), ('results', track_list)]) return Response(data) except: print "========= all_tracks() Expection =======" data = OrderedDict([('count', 0), ('next', None), ('previous', None), ('results', 'Failed To display tracks')]) return Response(data) """Creating new Track.""" try: if request.method == 'POST': try: load = request.data title = load['title'] music_info = Music.objects.create(title=title) for genre in load['genres']: try: genere_obj = Genere.objects.get(id=genre) music_info.genere.add(genere_obj) except: pass data = {'message': 'Track added'} try: rate = int(load['rating']) if load['rating'] != '': if rate in range(1, 6): rating = rate Rating.objects.create(music=music_info, user=request.user, rating=rating) data['message'] += ', Rating updated' except: data[ 'message'] += ', Rating Adding Failed, Please make sure You are loggedin' return Response(data) except: pass except: print "========= all_tracks() Expection =======" data = OrderedDict([('count', 0), ('next', None), ('previous', None), ('results', 'Failed To add track')]) return Response(data)