Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 360
pbreak Avatar asked Jan 29 '18 17:01

pbreak


1 Answers

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

like image 119
The Coder Avatar answered Nov 14 '22 21:11

The Coder