Django Views & Django Rest Framework Views
Target Audience: People who have a hand on experience in WebDev especially Django.
Remember: URLs are mapped to Views.
Django View is a python function that takes a Web Request and returns a Web response. Both Django View & DRF Views can be function based & class based. Function based is used mainly with Django & Class based with DRF.
The hierarchy goes like this
- Django (It has function based Views mainly)
1.1 Django Rest Framework [DRF] (It has class based views mainly)
In Django Based Views the URLs are mapped to Views using paths, conf.urls. Now, when “user/” endpoint is hit, “userdetails” view is called.
Moving forward with the hierarchy
- Class Based Views (ViewClass)
1.1 ViewSetClass (It includes ViewSet, ModelViewSet, GenericViewSet, ReadOnlyModelViewSet)
We saw in the Table1.0 DRF View Based Example that ViewClass has “get” & “post” functions(Of APIView) defined in it whereas ViewSetClass uses actions such as .list() & .create() instead of get(), post() methods.
An example of ViewSetClass can be viewed in Picture2.0 (The AdminBasedModelViewSet is a ViewSetClass)
A ViewSetClass is simply a type of class-based view, that does not provide any method handler such as .get() or .post(), instead provides actions such as .list() & .create().
In other frameworks, you may also find conceptually similar implementations named something like ‘Resources’ or ‘Controllers’
In ViewSetClass the URLs are mapped to Views using Routers. When routers are used we have to use ViewSetsClass and not APIView.
When I hit “doctor/”, DoctorModelViewSet is called which inherits AdminBasedModelViewSet.
Now, one must be thinking that with the help of routers I’m able to reach the desired view but then how will my get and post call get executed.
The magic is in AdminBasedModelViewSet(Which is created by me) which is a ModelViewSet using actions such as .list(), .create(), etc.
The ViewSet automatically calls .list() function if it is a GET call & .create() function if it a POST call. We have defined when to use “get” & “post” in our .list() & .create() logic.
(Here, we have overwritten the .list() and .create() logic for our own benefit. It is not necessary to overwrite it. The “get” & “post” methods are by default defined in “.list()” and “.create()” actions respectively by DRF.
Conclusion
RegularViews + URLConfs is more explicit & gives more control.
ViewSetClass + routers -> Repeated logic can be combined into a single class. We can reuse the code & no longer need to deal with wiring up the URLConf ourselves.
It follows the DRY principle (Don’t Repeat Yourself)
The code is then easy to understand because the design becomes very systematic. The design follows a hierarchical pattern.
Using ViewSetClass is also regarded as a good coding practice.
Follow the documentation for more learning.