Branch: master
Find file Copy path
98 lines (76 sloc) 2.95 KB
Basic building blocks for generic class based views.
We don't bind behaviour to http method handlers yet,
which allows mixin classes to be composed in interesting ways.
from __future__ import unicode_literals
from rest_framework import status
from rest_framework.response import Response
from rest_framework.settings import api_settings
class CreateModelMixin(object):
Create a model instance.
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(
headers = self.get_success_headers(
return Response(, status=status.HTTP_201_CREATED, headers=headers)
def perform_create(self, serializer):
def get_success_headers(self, data):
return {'Location': str(data[api_settings.URL_FIELD_NAME])}
except (TypeError, KeyError):
return {}
class ListModelMixin(object):
List a queryset.
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(
serializer = self.get_serializer(queryset, many=True)
return Response(
class RetrieveModelMixin(object):
Retrieve a model instance.
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
return Response(
class UpdateModelMixin(object):
Update a model instance.
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance,, partial=partial)
if getattr(instance, '_prefetched_objects_cache', None):
# If 'prefetch_related' has been applied to a queryset, we need to
# forcibly invalidate the prefetch cache on the instance.
instance._prefetched_objects_cache = {}
return Response(
def perform_update(self, serializer):
def partial_update(self, request, *args, **kwargs):
kwargs['partial'] = True
return self.update(request, *args, **kwargs)
class DestroyModelMixin(object):
Destroy a model instance.
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
return Response(status=status.HTTP_204_NO_CONTENT)
def perform_destroy(self, instance):