ViewSets and Routers - django-rest-framework part 3

ViewSets and Routers are very useful for slimming up your code and providing a lot of default functionality out of the box. They are powerful features in django-rest-framework allowing a lot of flexibility in your code while keeping things clean.

resources

api/urls.py

from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns

from api.views import task_list, task_detail

urlpatterns = patterns(
    'api.views',
    url(r'^tasks/$', task_list, name='task_list'),
    url(r'^tasks/(?P<pk>[0-9]+)$', task_detail, name='task_detail'),
)

urlpatterns = format_suffix_patterns(urlpatterns)
gotodo/urls.py
from django.conf.urls import patterns, include, url

from api.views import task_router

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns(
    '',
    url(r'^api/', include(task_router.urls)),
    url(r'^admin/', include(admin.site.urls)),
)
views.py
from rest_framework import viewsets
from rest_framework.routers import DefaultRouter

from task.models import Task
from api.serializers import TaskSerializer
from api.permissions import IsOwnerOrReadOnly


class TaskMixin(object):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer
    permission_classes = (IsOwnerOrReadOnly,)

    def pre_save(self, obj):
        obj.owner = self.request.user

class TaskViewSet(TaskMixin, viewsets.ModelViewSet):
    pass

task_list = TaskViewSet.as_view({
    'get': 'list',
    'post': 'create'
})

task_detail = TaskViewSet.as_view({
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
})

task_router = DefaultRouter()
task_router.register(r'tasks', TaskViewSet)
comments powered by Disqus