I am creating a REST API using Django Rest Framework. The API will serve large amount of data and I want to use infinite scrolling on the page. I would like to use Angular for the frontend. I am not sure how to serve the data such that not all data has to be sent once but only when the user scrolls down.
I am using serializer class -
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = ('company_name', 'location', 'founded_year')
I am not sure about how to implement this. Should i use Django Endless Pagination or could it be done by using the pagination provided by django-rest-framework. I am also not sure about how the frontend of this would work. Web development newbie here, please help.
Create a ListAPIView subclass
from rest_framework import pagination, generics
class CompanyPagination(pagination.PageNumberPagination):
page_size = 20 # the no. of company objects you want to send in one go
# Assume url for this view is /api/v1/companies/
class CompanyListView(generics.ListAPIView):
queryset = Company.objects.all()
serializer_class = CompanySerializer
pagination_class = CompanyPagination
Once this is done, you can get first 20 by calling the http://your_domain.com/api/v1/companies/?page=1, ?page=2
will give 21st company to 40th company and so on. (Not specifying ?page=
is like doing ?page=1
)
On your AngularJS
side, you will maintain some variable which will hold which page number to fetch next. Now you can bind your API request to either click event on some Load More type of button, or may be you can detect whether user has scrolled to the bottom, and then do the API request and fetch next set of Company
objects.
Note:
It is not compulsory to use PageNumberPagination
, you can even use LimitOffsetPagination
or CursorPagination
to achieve your objective. Read more about various pagination styles here
You should give CursorPagination a try. I don't know exactly whether it's infinite or not but it's definitively for huge sets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With