P8 -Adding Pagination to ViewSets

Lets see how to add pagination to viewset. As will all other things in django, this is super easy

Assuming you have already done the the tutorial P6 – Django – Viewsets it is possible that we might need pagination on some of the rest calls. So we may have a lot of data on the server and sending it all at once back to the client may not be required and may not be the efficient way to handle the data. The client on the other hand might need only a handful of data and would not want all the data which will become difficult to process. So Lets see how do we set up pagination on view sets.

lets take example of rest services which returns “Ads” and it may have thousands of ads. At any point of time the client will need only a handful of them to process. So the client must be able to pass the rest service some parameter identifying the page number it desires.

For our example. We create a pagination.py file and add below content.

from rest_framework.pagination import PageNumberPagination

class PaginationMeta(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    max_page_size = 10000

Here we have set three parameters. One is the “page_size” which means the amount of data the server will send if requested with page number i.e with parameter “page” . The next is “page_size_query_param” which can be used if want a specified number of records to be retrieved and override the page_size. “max_page_size” which is the max page size for our request.

The next step is to set this class in our viewset as below.

from django.shortcuts import render
from .models import Ads
from .serializers import AdsSerializer
from rest_framework import viewsets
from .pagination import PaginationMeta
# Create your views here.

class AdsView(viewsets.ModelViewSet):
    queryset = Ads.objects.all()
    serializer_class = AdsSerializer
    pagination_class = PaginationMeta

Here we set the pagination_class to the PaginationMeta we created. And this is all we will have to do to set up pagination. I am providing other classes required for this example.

from django.db import models

# Create your models here.

class Ads(models.Model):
    category = models.CharField(max_length=50)
    city= models.CharField(max_length=50)
    email = models.CharField(max_length=50)
    brand = models.CharField(max_length=50)
    make = models.CharField(max_length=50)
    capacity = models.CharField(max_length=50)
    desc = models.CharField(max_length=150)
    price = models.FloatField(max_length=20)
from rest_framework import serializers
from .models import Ads

class AdsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ads
        fields = ['id','category', 'city','email','brand','make','capacity','price','desc']
from rest_framework.routers import DefaultRouter
from . import views
from django.urls import path, include

router = DefaultRouter()
router.register('ads', views.AdsView)

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

Now we have set the url pattern for our views to “/ads” so to access the views so a call to http://localhost:8000/api/ads/ will return the first page as below.

Content-Type: application/json
Vary: Accept

    "count": 17,
    "next": "http://localhost:8000/api/ads/?page=2",
    "previous": null,
    "results": [
            "id": 1,
            "category": "Cars & MotorCycles",
            "city": "Pune",
            "email": "",
            "brand": "MARUTI",
            "make": "Brezza",
            "capacity": "1.2",
            "price": 123213.0,
            "desc": "dadsadsad"
            "id": 2,
            "category": "Cars & MotorCycles",
            "city": "Pune",
            "email": "",
            "brand": "HYUNDAI",
            "make": "I20",
            "capacity": "1.2",
            "price": 34324234.0,
            "desc": "asdsadsads"
            "id": 3,
            "category": "Cars & MotorCycles",
            "city": "Pune",
            "email": "",
            "brand": "MARUTI",
            "make": "Brezza",
            "capacity": "1.2",
            "price": 122132.0,
            "desc": "sadsadad"

As you can see, it has returned with the first page and also various others attributes to navigate to next page. We can jump to any page we wish by providing the page parameter to the url e.g. http://localhost:8000/api/ads/?page=4

Please let us know if you liked this post and if it helped you. Thank you for spending time reading my post.

P7 – Django – Relationships

GIT LINK – https://github.com/letsblogcontent/SampleRestProject/upload/master
So till in the previous tutorials we have different ways to configure views and models but we have seen basic examples and there were no relationships between models which hardly happen in the real world. In most cases models have relationship between each other.

Lets see how to create relationship between our product and company model. So earlier we created two models, product and company but there was no relationship between them. So ideally each product is produced by a company. So there is one to one relation between a product and company. a product is associated with one and only one company.

Step 1

Lets implement this in our models. Before starting lets flush out the data we created from our previous tutorials using the command “python manage.py flush”


Step 2

Now update our models to create the relationship between Product and Company.

We have here created a company variable in the Product model and used the ForeignKey Api to in the models class to create the relationship. We have also mentioned what should happen when a record is deleted using the on_delete parameter. In our case we do not want anything to happen in the company model when a product record is deleted. The parameter blank = False means that the field cannot be blank. There are several other parameters that we can set for a field. You can check them out at the django documentation

Update the product serializer to have company

There is no change required in the view class and also no change required in the urls.py file. Now lets see how does the database table of product look like.

See, a new column company_id is added to the product table which refers to the primary key of the company table.

Step 3

Lets add a company and try adding a product afterwards and with a company associated with it.

We add a new company

Notice that when we retrieve we receive only the company id and not the entire company object with details. Lets make a simple change to retrieve entire company object details instead of the id.

update the serializer of the product to with a reference to company serializer as below.

Now lets see the output.

We can add different relationships other than Foreign key, like the onetoone of manytomany. The implementation is similar to the above with change in the api. Rest of the things will mostly remain the same

P6 – Django – Viewsets

GIT LINK – https://github.com/letsblogcontent/SampleRestProject/upload/master

Django also provide a more higher level of abstraction for the model and the views called as ViewSets. This abstractions allows developer to concentrate on the modelling and the state rather than url construction. It is very slightly different than the view creating view classes but with viewsets we have to write less code and it makes more sense as lot of the repetative code is abstracted and we can choose to overwrite if required.

Step 1

Lets continue from where we left and create a new model known as User in models.py file and execute makemigrations and migrate command to create this new model.


Once the model is created run the command “python manage.py makemigrations” and then “python manage.py migrate

Step 2

Similar to previous tutorials, we create a standard serializer


Step 3

Now lets create a new viewset for User model as below by extending the ModelViewSet Class.


remember with class based views, we had to create view classes for list views and the model view. But here we are creating only one viewset class.

Step 4

Update the urls.py file as below. Notice that we just have to register the viewset to router and all the urls configuration will be abstracted for us and will be handled by the Router. So this has reduced our code of creating list view and also creating a different url patterns


Step 5

Now lets test and see it in action. So this should serve our purpose for time being. We will look at different scenarios and ways to handle in the next tutorial

P5 – Django Rest – Mixins

So till now we have seen all things that we need to write or configure to make a new rest api and configure new endpoints. A lot of code in a model based structure is repetitive if you look closely. A model needs to respond to GET , POST, PUT , DELETE requests etc through a view. Mixins allow us to fire a new endpoint with all the default functions really fast and we dont need to write all the code that we wrote in previous tutorials. So all we have to do is create our model, serializer and map it to a url. The view also needs update but its very simple, a lot of handling will be done by the framework. Let look at an example.


Suppose we need an endpoint for company. So create a model and serializer like below


Step 2

Now mixins provides a bunch of different ways to configure your view. We will look at one of them. But you can explore other configurations as well based on your need.

Create two classes in the views.py file, one to list all the companies and accept a post request to add a company and other to access a single company or delete a single company which will handle GET, PUT, DELETE request.

Notice the mixins used in the CompanyListView, one is the ListModelMixin and other is the CreateModelMixin Mixin. One to list the data and other to create. All we do here is tell the class where to fetch the objects from and which is the serializer class using the queryset variable and the serializer_class variable. Then we have defined two methods GET and POST and used the list and create methods from the mixins to list or create a new object.

Now let looks at more concise way of writing the above functionality on the company view with which we can retrieve a single company or delete a company.


Notice we have extended from RetrieveDestroyAPIView class from generics. This will abstract everything for us and all that we have to provde is the queryset and serializer_class and its done.

So we have now configured the CompanyView and CompanyListView. Now lets add them to the urls.py file.


Step 3

Lets run and see this api in action.

Get all companies
Get company by id

GIT Project link – https://github.com/letsblogcontent/SampleRestProject

P4 – Django Rest – Class Based Views

In the previous tutorial we have seen how to create rest api and add GET, POST request using independent functions. Now we will see how to create class based views. So with a class based views we can have more separation of concerns of different parts of our application wrapped within a class serving different http requests.

Step 1

It is very simple and aimed at reducing and creating reusable code. Lets create model having seller information as below in the models.py file.


Step 2

Now create a serializer class for the Seller class in the serializer.py file as below


Step 3

Now in the views.py file we define a new class “SellerView” which extends it self from the APIView class. The APIView class is a wrapper class which provided additional standard handling of the various http requests thus abstracting us from the finer details and we can write our functionality faster and in an efficient way. Notice that we have created two methods, one for GET request and one for POST request. The framework will automatically invoke respective methods based on the HttpRequest.

Ignore the additional imports for generics and mixins, we will need them later, we can ignore them for now.

Also note that we have used the format variable and set it None, it means that the function can handle multiple formats. Res t of the code is pretty standard that we have seen in earlier tutorials

Step 4

Now we need to map url pattern to this new Seller class view. See below screenshot where we have added the seller url pattern, we need to pass the as_view return unlike functions itself that we passed earlier with function based views and its done.

Step 5

Its time to test. Lets open the ARC and add one new seller to the rest service and then retrieve it back.

Add new seller to the service
Retrieve the seller back

GIT Project link – https://github.com/letsblogcontent/SampleRestProject

P3 – Django Rest – Parameter in URL

So we have now completed how to add a GET request and how to add a POST request. Lets look at an example on how to add a url parameter to the request and use it to fetch data. It is extremely simple. Let look at the steps


Update the urls.py file as below to parse the integer field that we will pass from in the rest request. The integer field will be the primary key of the product object that we stored earlier in the tutorials. Notice we have added <int:pk>
as part of the url pattern which indicates django to map any request with integer values after the product to the get_product function in the views.py we defined in the previous step

Step 2

Now lets move to views.py file in the products app and create a new method to handle the get request for a particular object. Notice how we have passed the pk parameter to this method, this will be the parameter that we will pass in the rest request as the pk of the object that we want to respond with. We will use the serializer created in our previous tutorials to serialize the fetched object and send the response back

Step 3

Now lets look at sample request through ARC chrome plugin. Notice we have sent 4 as the pk of the Product object that we want to retrieve and we have received the response back from the server in json format.

GIT Project link – https://github.com/letsblogcontent/SampleRestProject

P2 – Django Rest – Post Request

In the previous tutorial we have created a simple rest framework and configured a “GET” request and successfully displayed data from the server through Django Rest framework. Now lets learn quickly how to add a POST request so that we can add new products through a rest call and then view it later.


Lets first define a new function in the views.py file in the products app and decorate it with POST attribute of the api_view annotation. Lets call this function as add_product. We fetch the data into the serializer instance of ProductSerializer and then check if the object is a valid Product object. This will confirm if we have received correct types in the fields as defined in our Product class. Once it is termed valid by the framework, we save it into the database.

Step 2

Now that we have defined the function we need to call, we need to configure the url that it should map to. So lets go the url.py in the products app and configure “product” to map to our newly defined function.

Step 3

And we are done with our project configuration. Now lets send a rest call to our server with the product object and check if the save was successful. I am using ARC(Advanced Rest Client) to send the rest request, you can use any one you like.

As you can see I have received a successful response back from the server. I have save a new product having name “Samsung X2” Make sure to choose a correct content type and POST method as shown else it will result into an error.

Step 4

Now lets retrieve the data of all the products and see if the data is saved.

Create Spring Boot Application in 5 min


Below tools should be installed on your machine

  1. Java
  2. Maven
  3. STS/Eclipse

GO to https://start.spring.io/

Add dependency as Spring Boot DevTools

Kindly add required dependencies as shown in above screenshot and down load project by clicking on “GENERATE” button. ZIP will get downloaded.

NOTE: Kindly select java version according to your project need ..I am using java 1.8 else you will get below exception when you run mvn clean install

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven: Compilation failure: Compilation failure

NOTE: if you are downloading on office laptop then you might need to unblock zip before unzipping. for doing this right click on zip file and go to properties and unblock it. so you will able to unzip it completely.

After unzip you will see folder generate like below screenshot

Go to your editor and import project.

For eclipse or STS Users..

1 GO to file

2 click on import

3 type maven and select Existing maven project

4 It will show pop up to select folder of your project. Kindly select folder which you unzipped.

5 Select pom.xml and click on Finish button

6. Now your project will get created in workspace and all dependencies will get downloaded by maven.Make sure maven is installed on your machine.

In below screenshot and in highlighted part you can see its showing “boot” project in bracket because spring tool suit will automatically detect it as spring project. For this in eclipse you need to download plugins.

Your project will be visible in workspace now

7. Right click on project and go to run and do maven install as shown in below screen shot

On console you will see below logs

8. Once build is successful then add below code in DemoApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	System.out.println("Welcome to spring boot");


9. Now Run application as spring boot app shown in below screenshot

10. Congrats now your application is running succesfully

Create your website with WordPress.com
Get started