Binding ViewSets to URLs explicitly

The handler methods only get bound to the actions when we define the URLConf.To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.

In the snippets/urls.py file we bind our ViewSet classes into a set of concrete views.

  1. from snippets.views import SnippetViewSet, UserViewSet, api_root
  2. from rest_framework import renderers
  3. snippet_list = SnippetViewSet.as_view({
  4. 'get': 'list',
  5. 'post': 'create'
  6. })
  7. snippet_detail = SnippetViewSet.as_view({
  8. 'get': 'retrieve',
  9. 'put': 'update',
  10. 'patch': 'partial_update',
  11. 'delete': 'destroy'
  12. })
  13. snippet_highlight = SnippetViewSet.as_view({
  14. 'get': 'highlight'
  15. }, renderer_classes=[renderers.StaticHTMLRenderer])
  16. user_list = UserViewSet.as_view({
  17. 'get': 'list'
  18. })
  19. user_detail = UserViewSet.as_view({
  20. 'get': 'retrieve'
  21. })

Notice how we're creating multiple views from each ViewSet class, by binding the http methods to the required action for each view.

Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.

  1. urlpatterns = format_suffix_patterns([
  2. path('', api_root),
  3. path('snippets/', snippet_list, name='snippet-list'),
  4. path('snippets/<int:pk>/', snippet_detail, name='snippet-detail'),
  5. path('snippets/<int:pk>/highlight/', snippet_highlight, name='snippet-highlight'),
  6. path('users/', user_list, name='user-list'),
  7. path('users/<int:pk>/', user_detail, name='user-detail')
  8. ])