【问题标题】:JQuery talking to DJango REST API. Need to return number of pages in responseJQuery 与 DJango REST API 对话。需要返回页数作为响应
【发布时间】:2018-06-23 17:01:07
【问题描述】:

我是 Django REST 框架的新手。我有一个包含列表页面的应用程序。加载页面时,JQuery 应该与 API 对话,当收到响应时,它应该显示可用艺人的列表,我需要对其进行分页。 我有分页工作,但目前有硬编码的页面链接数量。我需要记录总数或 API 响应中返回的页面数,以便我可以在模板中动态构建链接 我尝试了几种方法,但都没有成功 首先从我的 views.py 传入响应,它使用基于类的视图

if self.request.GET['page'] is not None:
    if self.request.GET['page'] != 'all':
        page = self.request.GET['page']

recordsPerPage = 8
paginator = Paginator(entertainers, recordsPerPage)
total_records = paginator.count
num_pages = paginator.num_pages
entertainers = paginator.page(int(page))

return Response({
   'count': paginator.count,
   'num_pages': paginator.num_pages,
   'results': serialized_data
})

这产生了“内部服务器错误”

我尝试这样做的另一种方法是在我的 serializers.py 文件中添加一个自定义字段,但它也给出了内部服务器错误

class EntertainerSerializer(serializers.ModelSerializer):
    my_field = serializers.SerializerMethodField('record_count')

    def record_count(self, foo):
        return foo.name == "10"

class Meta:
    model = Entertainer
    fields = (...,'my_field')

我的 JQuery 是

var populateTemplate = function(){
    $('#REST-data').html('');

    var restDataDiv = $('#REST-data');
    for(i=0;i<apiResponseArr.length;i++){
        var card = $('<div class="col-lg-3 col-md-6 col-xs-12 margin-top-1"><a href="/entertainers/profile/'+apiResponseArr[i].id+'"><div class="card h-100"><img class="card-img-top" src="'+apiResponseArr[i].profile_image_url+'" class="img-fluid center-block img-thumbnail" style="max-height:150px;" alt="'+apiResponseArr[i].profile_image_url+'" /><div class="card-body"><h4 class="card-title">'+apiResponseArr[i].title+'</h4><p class="card-text">'+apiResponseArr[i].bio_summary+'</p></div></div></a></div>');

        restDataDiv.append(card);
    }
};

var requestForJsonData = function(description,location,callingFunction, page){
    var host = window.location.hostname;

    // IF RUNNING ON LOCALHOST
    var entertainerAPI = 'http://' + host + ':8000/entertainers/api/listings/?';

    $.getJSON(entertainerAPI,{description: description,location: location, page: page}, function(){
        console.log('success');
    }).done(function( json ) {
        apiResponseArr = json;
        // Check which function called the requestForJsonDat function
        if('refineSearch' == callingFunction || 'initLoad' == callingFunction){
            //  Call to populate the templates with the JSON data
            populateTemplate();
        }
    }).fail(function(jqxhr, textStatus, error){
        var err = textStatus + ", " + error;
        console.log( "Request Failed: " + err );
    });

};

var refineSearch = function(menus){
    var description = 'all';
    var location = 'all';
    var page = 'all'
    /*  Build click event for the refine button */
    $('#refine-button').click(function(){
        description = $('#description-select').val();
        location = $('#location-select').val();
        requestForJsonData(description,location,'refineSearch',page);
    });

    $('.listing-pager').click(function(){
        var page = $(this).text();
        description = $('#description-select').val();
        location = $('#location-select').val();
        requestForJsonData(description,location,'refineSearch',page);
    });
};

我在模板中的每一个页面链接都有一个“listing-pager”类

<a href="#" class="listing-pager">1</a>
<a href="#" class="listing-pager">2</a>

有什么想法吗?

【问题讨论】:

    标签: jquery django pagination django-rest-framework serialization


    【解决方案1】:

    在 settings.py 中添加以下代码

    REST_FRAMEWORK = {
      'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.LimitOffsetPagination',
      'PAGE_SIZE': 100
    }
    

    使用通用 ListAPIView 见下例

    from rest_framework.generics import ListAPIView
    
    class PaginatedListView(ListAPIView):
        queryset = ExampleModel.objects.all()
        serializer_class = ExampleModelSerializer
        paginate_by = 50
    

    参考资料:
    http://www.django-rest-framework.org/api-guide/pagination/
    http://djangorestframework.readthedocs.io/en/latest/api-guide/pagination/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 2021-05-10
      相关资源
      最近更新 更多