1. Home
  2. Docs
  3. Django Rest Framework
  4. Pagenation

Pagenation

Create Django Project:

First, create a new Django project named pagination_example:

django-admin startproject pagination_example
Bash

Create Django App:

Create a Django app named myapp within the project:

cd pagination_example
python manage.py startapp myapp
Bash

Define the Model:

Define the Item model in models.py of your app (myapp/models.py):

from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)

    def __str__(self):
        return self.name
Bash

Migrate the Database:

Apply the migrations to create the Item model’s table in the database:

python manage.py makemigrations
python manage.py migrate
Bash

Admin Interface (Optional): Register the Item model with the Django admin for easy management:

In myapp/admin.py:

from django.contrib import admin
from .models import Item

admin.site.register(Item)
Bash

Views and Serializer: Create a serializer and a viewset for the Item model in serializers.py and views.py of your app (myapp/serializers.py and myapp/views.py):

# myapp/serializers.py
from rest_framework import serializers
from .models import Item

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = '__all__'

# myapp/views.py
from rest_framework import viewsets
from .models import Item
from .serializers import ItemSerializer

class ItemViewSet(viewsets.ModelViewSet):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer
Bash

URLs: Configure URLs in urls.py of your project (pagination_example/urls.py):

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from myapp.views import ItemViewSet

router = DefaultRouter()
router.register(r'items', ItemViewSet)

urlpatterns = [
    path('', include(router.urls)),
]
Bash

Pagination: Configure pagination in your settings.py:

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10  # Adjust the page size as needed
}
Bash

Run the Development Server: Start the Django development server:

python manage.py runserver
Bash

Access Data: You can now access your Item model data via the API.

Request

GET http://localhost:8000/items/
Bash

Response:

  • Let’s assume the instances returned are: Item1, Item2, Item3, Item4, and Item5. Since our page size is 2, the response will be paginated as follows:
{
    "count": 5,
    "next": "http://localhost:8000/items/?page=2",
    "previous": null,
    "results": [
        {
            "id": 1,
            "name": "Item1",
            "description": "Description of Item1",
            "price": "10.99"
        },
        {
            "id": 2,
            "name": "Item2",
            "description": "Description of Item2",
            "price": "19.99"
        }
    ]
}
Bash

Explanation:

  • "count": 5 indicates there are a total of 5 instances in the queryset.
  • "next": "http://localhost:8000/items/?page=2" provides the URL to the next page of results, if available. Since we only have 5 instances and the page size is 2, there is a next page.
  • "previous": null indicates there is no previous page as this is the first page.
  • "results" contain the instances for the current page, in this case, Item1 and Item2, along with their details like id, name, description, and price

How can we help?