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.

Step1

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

models.py
serializer.py

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.

view.py

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.

urls.py

Step 3

Lets run and see this api in action.

ARC POST
Get all companies
Get company by id

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with WordPress.com
Get started
%d bloggers like this: