Design a site like this with WordPress.com
Get started

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.

#models.py

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

#serializers.py

Step 3

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

#views.py

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

#urs.py

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:

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

%d bloggers like this: