我想将blog转为前后分离的模式,以前的页码使用Paginator分页后带的方法实现的
<div class="ui secondary menu"> {% if articles.has_previous %} <a href="?page=1" class="item"> <i class="angle double left icon"></i> </a> <a href="?page={{ articles.previous_page_number }}" class="item"> <i class="angle left icon"></i> </a> {% else %} <a href="#" class="disabled item"> <i class="disabled angle left icon"></i> </a> {% endif %} {% for i in paginator.page_range|range:articles.number %} {% if articles.number == i %} <a href="?page={{ i }}" class="active item">{{ i }}</a> {% else %} <a href="?page={{ i }}" class="item">{{ i }}</a> {% endif %} {% endfor %} {% if articles.has_next %} <a href="?page={{ articles.next_page_number }}" class="item"> <i class="angle right icon"></i> </a> <a href="?page={{ paginator.num_pages }}" class="item"> <i class="angle double right icon"></i> </a> {% else %} <a href="#" class="disabled item"> <i class="disabled angle right icon"></i> </a> {% endif %} </div>
可是现在没有办法将这些方法传出去了
我想在serializers的实例化后再往这个instance塞数据,请问怎么做呢?
贴上现有的代码
# serializers.py class ArticleModelSerializer(serializers.ModelSerializer): detail_url = serializers.SerializerMethodField() class Meta: model = Article fields = ('id', 'header', 'content', 'put_time', 'tag', 'click_rate', 'detail_url') def get_detail_url(self, obj): return reverse('detail', args=[obj.id, ''])
问题核心在下面这段代码中
# views.py class ArticlePage(APIView): def get_object(self, page_num): articles = Article.objects.all() paginator = Paginator(articles, 10) try: articles = paginator.page(page_num) return articles except EmptyPage: return paginator.page(paginator.num_pages) except PageNotAnInteger: return paginator.page(1) def get(self, request): articles = self.get_object(page_num=request.GET.get('page')) # 在这里的serializer塞入像总页数之类的数据,方便前端使用 serializer = ArticleModelSerializer(articles, many=True) return Response(serializer.data)
rest framework 有个自动分页功能 但是只有在使用通用视图或viewsets时,才会自动执行分页,类视图不行的。这个是关于分页的api文档http://www.django-rest-framework.org/api-guide/pagination/