Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference in use or inherit from APIView and Model ViewSet

I would meet the difference with respect to when use APIView and when use ModelViewSet when I want serialize my models with respect to get a list of their objects/records?

For example, in the APIView documentation we have that with the ListUser class and their get method we can get the list of users

class ListUsers(APIView):
    """
    View to list all users in the system.

    * Requires token authentication.
    * Only admin users are able to access this view.
    """
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAdminUser,)

    def get(self, request, format=None):
        """
        Return a list of all users.
        """
        usernames = [user.username for user in User.objects.all()]
        return Response(usernames) 

I have been get this same list of users using ModelViewSet of this way:

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    filter_fields = ('username', 'is_player', 'first_name', 'last_name', 'team' , 'email', )

How to can I identify when should I use APIView or ModelViewSet for this task?

like image 447
bgarcial Avatar asked Jan 26 '17 16:01

bgarcial


1 Answers

Question is too open though I'll try to answer it.

First thing first, APIView or ViewSet aren't tied to models while ModelViewSet, GenericAPIView, ListAPIView (and co) are.

The major difference between *View and *ViewSet is that *ViewSet are meant to work with routers and provide a single class to expose a Resource while *View will require two (one for list/create, another for detail/update/delete).

Note that APIView is the most lower level and will only tie to HTTP verbs (get/post/put...) while ViewSet or GenericAPIView will have CRUD such as list / update...

In order to expose a Django's Model, you'll need either

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

or

class UserListCreateView(ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
like image 99
Linovia Avatar answered Sep 26 '22 20:09

Linovia