Design a site like this with
Get started

P6 – Django – Viewsets


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 file and execute makemigrations and migrate command to create this new model.

Once the model is created run the command “python makemigrations” and then “python 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 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


Leave a Reply

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

You are commenting using your 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

%d bloggers like this: