List of available mixins:
.list()
method to the view/viewset.retrieve()
method to the view/viewset.create()
method to the view/viewset.update()
method to the view/viewset.destroy()
method to the view/viewsetWe can mix and match the mixins in our generic views and viewsets, in order to give them the corresponding utility that we need:
An API view with .list()
.create()
and .destroy()
methods?
Inherit from the GenericAPIView
and combine the appropriate mixins:
from rest_framework import mixins, generics
from myapp.models import MyModel
from myapp.serializers import MyModelSerializer
class MyCustomAPIView(mixins.ListModelMixin,
mixins.CreateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
A viewset with only a .list()
and .update()
methods?
Inherit from the GenericViewSet
and add the appropriate mixins:
from rest_framework import mixins
class MyCustomViewSet(mixins.ListModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
pass
Yes, it was that easy!!
To conclude, we can mix and match every mixin we need and utilize it to customize our views and their methods in any possible combination!