Difference between ViewSet, ModelViewSet and APIView - python

What are the advantages of ViewSet, ModelViewSet and APIView. In the django-rest-framework documents it is not clear, it does not say when to use ViewSet, ModelViewSet and APIView. I want to implement an API that will have a business logic in there, a great business logic with data processing as well, what should be used for this case?
I researched a lot and managed to understand a little about routers and urlpatterns but I didn't understand which one about views.

Summarizing: on one hand you have the APIView, which is the most generic of the three, but also in which you must do almost all business logic 'manually'. You have the class methods mapping http methods (get, post, ...) plus some class attributes to configure things like authentication, rendering, etc.
Often you'll be developing endpoints to interact with resources (entities, like Users, Products, Orders, etc.) via CRUD operations, and that is what ViewSet is for: they have more semantic class methods like list, create, retrieve ... that the router can then automatically map to urls and http methods at the expense of making some assumptions: for example, the retrieve assumes the http call to be GET /you_resource/<pk>. It is more rigid than a generic APIView but it takes away from you some boilerplate/manual config that you would have to repeat again and again in most cases.
One step further is the ModelViewSet, which is an extension of the ViewSet for when you are working with Django models. Just specifying a serializer_class and a queryset you have all the CRUD operations of the ViewSet ready to go. Obviously, you can also add your own methods to a ViewSet or customize the behavior of its default methods.
In my experience, it pays off to use ViewSets. The code looks cleaner and you avoid some boilerplate code. The assumptions it makes are reasonable, and I would even say that you probably will end up with a cleaner API design following them.

Related

Generic Views vs APIView vs Viewsets, vs ModelViewsets

I just started learning Django Rest Framework and I get to now about 4 concepts APIView, Viewsets, Modelviewsets, GenericView. What is the difference between them and which of them is more efficient to use in the development of rest APIs and why?
There is no standard but you can start with this simple strategy:
Several actions in one class and basic CRUD ---> Viewset (ModelViewSet and ReadOnlyModelViewSet are most useful)
Specific action on a model class ---> Generic Views (RetrieveModelMixin, ListAPIView, UpdateModelMixin, DestroyModelMixin, CreateModelMixin)
If you want to write all create, update, ... methods yourself you can use APIView and write them in your get, post, put, ... methods (Difference between APIView & GenericAPIView is only you cant use some builtin methods in your class , like queryset, serializer_class, ... )
And if you want to write everything from scratch you can write your apis in function base
Most of the times you have to write you apis with Generic Views & If you learn all of the Generic APIView best practices, it has so much power and your will be so clean, readable and scalable
Buy if you have simple Models you can use Viewset
I use GenericAPIView in normal APIs & use APIView in the custom ones (like most of APIs in Admin Panel)

What are the differences between Generics, Views, Viewsets and Mixins in Django?

I am new to Django and Django-Rest. I am confused about when I should use these? what are their advantages and disadvantages? I have only seen this- http://www.cdrf.co
The only thing I know is there are a lot of ways to do 1 thing. But this is totally unclear to me.
In Django, these four terms we use frequently for different purposes in the projects. I have tried to collect and share the actual meaning with the links to details description of each term. Please check if you find these helpful.
Generic views:
“Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.”
— Django Documentation
Read more details
Views:
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really. The view itself contains whatever arbitrary logic is necessary to return that response. This code can live anywhere you want, as long as it’s on your Python path. There’s no other requirement–no “magic,” so to speak. For the sake of putting the code somewhere, the convention is to put views in a file called views.py, placed in your project or application directory.
Read more details
Viewsets:
Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet. In other frameworks, you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides actions such as .list() and .create().
The method handlers for a ViewSet are only bound to the corresponding actions at the point of finalizing the view, using the .as_view() method.
Read more details
Mixins:
The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as .get() and .post(), directly. This allows for more flexible composition of behavior.
The mixin classes can be imported from rest_framework.mixins.
Read more details

CBV or Functional View for JsonResponse

I am new to creating API endpoints using Django. Which is a better way to handle API requests and process JsonResponse? Should I do it in a Class-Based View? Or a Functional View?
I would assumed CBV would be an overkill since people tend to use CBV for the generic-view inheritance. Since I am merely sending back a Json object, i would consider it unnecessary and thus a Functional view would suffice. However, I am not too sure what exactly are the other components of CBV and FV that would matter and make the difference.
If there is one view better over another view, can you please tell me with reasons why one is preferred over another.
Cheers.

Is it possible to call different function of class based views through different actions in template

I am new to django and i ahve gone through all the docs of django. right now if we give some link in template and defined that link in urls.py i.e which view is going to handle that link. like this url(r'^dashboard/gift/$', login_required(CouponPageView.as_view())),
But i have this little doubt can i call different function of a view on clicking different links present in template.
The idea behind a class-based view is not to serve multiple resources (the targets of the links in your template). The idea is that the class-based view implements methods for the various HTTP methods (i.e. get, post, put, delete, head).
So you can server an HTTP GET of a certain URI using the SomeView.get() method, or you can handle a POST to the same resource from the post() method in the same SomeView class. This is helpful to support object oriented code, as the different methods on the object will typically share some resources.
If you want to handle different URL's, write different View classes. If their functionality is similar, use inheritance to prevent code duplication. If their functionality is almost identical, use parameters in the urlpattern.
I think you need to study the URL dispatcher a little more: https://docs.djangoproject.com/en/dev/topics/http/urls/

Class Based Views VS Function Based Views

I always use FBVs (Function Based Views) when creating a django app because it's very easy to handle. But most developers said that it's better to use CBVs (Class Based Views) and use only FBVs if it is complicated views that would be a pain to implement with CBVs.
Why? What are the advantages of using CBVs?
The single most significant advantage is inheritance. On a large project it's likely that you will have lots of similar views. Rather than write the same code again and again, you can simply have your views inherit from a base view.
Also django ships with a collection of generic view classes that can be used to do some of the most common tasks. For example the DetailView class is used to pass a single object from one of your models, render it with a template and return the http response. You can plug it straight into your url conf..
url(r'^author/(?P<pk>\d+)/$', DetailView.as_view(model=Author)),
Or you could extend it with custom functionality
class SpecialDetailView(DetailView):
model = Author
def get_context_data(self, *args, **kwargs):
context = super(SpecialDetailView, self).get_context_data(*args, **kwargs)
context['books'] = Book.objects.filter(popular=True)
return context
Now your template will be passed a collection of book objects for rendering.
A nice place to start with this is having a good read of the docs (Django 4.0+).
Update
ccbv.co.uk has comprehensive and easy to use information about the class based views you already have available to you.
When I started with DJango I never used CBVs because of their learning curve and a bit complex structure. Fast forward over two years, I use FBVs only at few places. Where I am sure the code will be really simple and is going to stay simple.
Major benefit of CBVs and Multiple Inheritence that comes along with them is that I can completely avoid writing signals, helper methods and copy paste code. Especially in the cases where the app does much more than basic CRUD operations. Views with multiple inheritance are multiple times easier to debug that a code with signals and helper methods, especially if it is an unknown code base.
Apart from Multiple inheritence CBVs by provide different methods to do dispatching, retrieving templates, handling different request types, passing template context variables, validating forms, and much more out of the box. These make code modular and hence maintainable.
Some views are best implemented as CBVs, and others are best implemented as FBVs.
If you aren’t sure which method to choose, see the following chart:
SOME WORDS FROM TWO SCOOPS
Tip Alternative Apporach - Staying With FBVs
Some developer prefer to err on the side of using FBVs for most views and CBVs only for views that need to be subclassed. That strategy is fine as well.
Class based views are excellent if you want to implement a fully functional CRUD operations in your Django application, and the same will take little time & effort to implement using function based views.
I will recommend you to use function based views when you are not going to implement any CRUD on your site/application means your intension is to simply render the template.
I had created a simple CRUD based application using class based views which is live. Visit http://filtron.pythonanywhere.com/view/ (will/won't be working now) and enjoy. Then you will know the importance of it.
I have been using FBVs in most of the cases where I do not see a real opportunity of extending views. As documented in the docs, I consider going for CBVs if the following two characteristics suit my use-case.
Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching.
Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components.
Function-Based Views(FBVs) are:
Easy to use but the
Code is not reusable by inheritance.
Recommended to use
Class-Based Views(CBVs) are:
Too much learning curve because it's really complicated
Code is reusable by inheritance.
Not recommended to use (FBVs are much beter)

Categories