Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest framework - using viewsets

I read about the viewsets in django, but haven't fully understood everything..

When using a viewset in django, for example -

class SnippetViewSet(viewsets.ModelViewSet):
    """
    This viewset automatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.

    Additionally we also provide an extra `highlight` action.
    """
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)

    @detail_route(renderer_classes=[renderers.StaticHTMLRenderer])
    def highlight(self, request, *args, **kwargs):
        snippet = self.get_object()
        return Response(snippet.highlighted)

and Routing is like this

router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet)

In the comments in the View they say - "This viewset automatically provides list, create, retrieve,update and destroy actions."

EDIT:::

 @detail_route(methods=['post'])
    def register(request):
        serializer = UserSerializer(data=request.DATA)
        if serializer.is_valid():
            user = User.objects.create_user(
                username = serializer.init_data['username'],
                password = serializer.init_data['password'],
            )

            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  • How do I access each one of those methods? and How do I access the highlight method?
  • The url registered in the router is /snippets. Do I do snippets/create? or snippets/delete?
  • What does the ModelViewSet actually does to the url structure?
like image 408
Ofek Agmon Avatar asked May 22 '15 11:05

Ofek Agmon


People also ask

What is difference between Api_view and Viewset?

APIView allow us to define functions that match standard HTTP methods like GET, POST, PUT, PATCH, etc. Viewsets allow us to define functions that match to common API object actions like : LIST, CREATE, RETRIEVE, UPDATE, etc.

What is Queryset in Django REST Framework?

The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. The default behavior of REST framework's generic list views is to return the entire queryset for a model manager.

Can I use django and Django REST Framework together?

Django Rest Framework makes it easy to use your Django Server as an REST API. REST stands for "representational state transfer" and API stands for application programming interface. Note that with DRF you easily have list and create views as well as authentication.

Can we use django for REST API?

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.


1 Answers

You access those actions by specifying the corresponding HTTP method, which is a core idea in REST. Namely, using the HTTP methods to do what their name implies.

  • GET /snippets/ - list the snippet objects
  • POST /snippets/ with POST data - create a new object
  • PATCH /snippets/ with data - create a new object
  • GET /snippets/42 - retrieve object with a primary key of 42
  • PUT/PATCH /snippets/42 - update object with the primary key of 42
  • DELETE /snippets/42 - delete object with the primary key of 42

To see all the generated and inferred URL regexes, put Django in debug mode and issue a request to an invalid URL. It will print out something like:

Using the URLconf defined in my_app.urls, Django tried these URL patterns, in this order:
^ ^$ [name='api-root']
^ ^\.(?P<format>[a-z0-9]+)$ [name='api-root']
^ ^AltEmail/$ [name='altemail-list']
^ ^AltEmail/\.(?P<format>[a-z0-9]+)$ [name='altemail-list']
^ ^AltEmail/(?P<pk>[^/.]+)/$ [name='altemail-detail']
^ ^AltEmail/(?P<pk>[^/.]+)/\.(?P<format>[a-z0-9]+)$ [name='altemail-detail']
[...]
like image 200
Ross Rogers Avatar answered Sep 20 '22 23:09

Ross Rogers