I use generics and plain urls for my REST API, but now I stuck with problem: I want custom actions, simple views to make some things with my models, like \"run\", \"publish\
The difference between Generics or ModelViewSet is that:
Convenient
Usually ModelViewSet is more convenient. Because ModelViewSet support creating url pattern automatically with DRF router. But Generics don't. you do yourself.
Shorten and crispy code
If you want to create CRUD, Generics needs two classes(ListCreateAPIView and RetrieveUpdateDestroyAPIView). But ModelViewSet needs only one class(ModelViewSet).
Check out Declaration below. Both inherits from GenericAPIView and mixins.CreateModelMixin, mixins.ListModelMixin It provides equivalent functionality basically. It depends on what you prefer. But I usually use ViewSet in most cases.
Declaration
# Generics __________________________________
class ListCreateAPIView(mixins.ListModelMixin,
mixins.CreateModelMixin,
GenericAPIView):
# ModelViewSet _____________________________
class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet):
# GenericViewSet _____________________________
class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
Example code
# Generics __________________________________
from rest_framework import generics
class BookList(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
# ModelViewSet _____________________________
from rest_framework import viewsets
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer