What is the difference between mixins and generics?
Asked Answered
G

1

5

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?

Guilford answered 7/4, 2019 at 23:22 Comment(2)
Possible duplicate of What are the differences between Generics, Views, Viewsets and Mixins in Django?Sky
If you ever have the time, I strongly suggest going through this comprehensive django CBV guide - it's long, but well worth reading, it should clarify all doubts related to mixins and what not.Coadjutrix
C
6

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.

Commandeer answered 8/4, 2019 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.