Jeroj82
Jeroj82

Reputation: 401

Angular and Django Rest framework. Issue with pagination in api

I have a little problem. In Rest framework settings I have:

REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAdminUser",),
    "PAGE_SIZE": 50,
    "DEFAULT_AUTHENTICATION_CLASSES": (
        'rest_framework.authentication.BasicAuthentication',
        'banner_compare.authentication.CsrfExemptSessionAuthentication',
    )
}

And in my API view, I have this line: (I have few pages in API, each pages has 50 elements)

 "next": "http://0.0.0.0:8000/api/something/?page=2",

In angular service:

  .factory('Something',["$resource", function ($resource){
return $resource(
    "/api/something/:something_id/", {something_id: '@id'},
    {
        query: {
            isArray: true,
            transformResponse: function (data) {
                var items = angular.fromJson(data);
                return items.results;
            }
        },
        update: {
            method: "PUT",
        }
    },
    {
        stripTrailingSlashes: false
    }
);
}])

And now, when I'll try to get all of this elements

$scope.somethings = Something.query();

I get only this 50 first elements. I get only first page from API. How can I get all of this elements without something like this:

"PAGE_SIZE": 50000000,

:)

But also I want to have pagination in API view.

Upvotes: 1

Views: 537

Answers (2)

Collin Reynolds
Collin Reynolds

Reputation: 397

If I were you I would grab each successive page once the page is retrieved from the server. In this way your web app will be more responsive as well rather than waiting for a gigantic query.

For instance:

$scope.grabPage = function(page) {
    page = page || 1;
    Something.query(
      {page:page},
      function(result) {
        $scope.somethings = $scope.somethings.concat(result);
        $scope.grabPage(page + 1);
      }
    );
};
$scope.somethings = [];
$scope.grabPage();

Upvotes: 0

Ross Rogers
Ross Rogers

Reputation: 24228

Specify the PAGINATE_BY_PARAM in your settings.py:

REST_FRAMEWORK = {
    [...]
    'PAGINATE_BY_PARAM': 'page_size',
}

Then you can append something like &page_size=42 on any request.

Upvotes: 1

Related Questions