Jacobo
Jacobo

Reputation: 1391

What is the difference between mixins and generics?

I'm learning about the Django Rest Framework. And there are two concepts that from my point of view are almost the same, and they are used in different scenarios.

rest_framework mixins I think that they are used when we use viewsets. And rest_framework generics are used with APIViews.

What is the difference between these two components?

Upvotes: 5

Views: 5236

Answers (1)

Dwight Gunning
Dwight Gunning

Reputation: 2525

The generics and mixin modules are indeed different, yet they are inter-related.

Django Rest Framework (DRF) separates ReSTful API / HTTP verb behaviour from Django model operations and organises a set of abstract/base classes for each. The ReSTful functionality is in APIView, GenericAPIView and ViewSetMixin. The Model related operations are implemented in the mixin module.

DRF then makes use of Python's multiple inheritance, and the "mixin" pattern, to combine these together into higher-level classes that are both useable and extensible.

The generic views and the concrete ModelViewSet both inherit from APIView in addition to composing functionality via the mixin classes.


Though not related to the question, the following observation about ViewSets may be helpful...

The following is the intro to ViewSets on the DRF site that might make things seem more complicated than they really are...

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.

Rather than inheriting the ViewSet directly, in many cases, it will make the most sense to inherit a ModelViewSet and combine it with a DefaultRouter. The ModelViewSet obtains the method handlers via the various mixin classes, and the DefaultRouter provides the 'action' function mapping.

In combination, all the basic REST actions can be performed on a given Model, with very little code.

Upvotes: 6

Related Questions