This page looks best with JavaScript enabled

API of Serializer and ViewSet in restframework

 ·  ☕ 4 min read

1. Serializer

1.1 Data Validation

When deserializing data, the validity of the data needs to be checked. At this point you can call is_valid() for validation, and if a validation error occurs, you can get the error message from the .errors attribute. For example:

1
2
3
4
serializer.is_valid()
# False
serializer.errors
# {'created': [u'This field is required.']}

The .is_valid() method takes an optional raise_exception flag; if a validation error exists, it throws a serializers.ValidationError exception.

1
serializer.is_valid(raise_exception=True)

Besides using explicitly declared validation rules, you can also specify custom field-level validation by adding a .validate_<field_name> method to a Serializer subclass. This is similar to Django forms’ .clean_<field_name> method.

1
2
3
4
class SnippetSerializer(serializers.Serializer):
    def validate_title(self, value):
	    # do something
        return value

You can also define custom validators, which will not be described in detail here.

The Serializer class inherits from BaseSerializer and has several methods that can be used to customize serialization behavior:

  • to_internal_value(self, data), used for deserialization, writing data
  • to_representation(self, instance), used for serialization, reading data
  • update(self, instance, validated_data), used to update data
  • create(self, validated_data), used to add data
  • save(self, **kwargs), the save operation

2. APIView

  • renderer_classes, the renderer classes
  • parser_classes, the parser classes
  • authentication_classes: the permission classes
  • throttle_classes: the throttling classes
  • permission_classes: the permission classes
  • content_negotiation_class: the content negotiation class
  • get_renderers(self), gets the renderers
  • get_parsers(self), gets the parsers
  • get_authenticators(self), gets the authenticators
  • get_throttles(self), gets the throttles
  • get_permissions(self), gets the permissions
  • get_content_negotiator(self), gets the content negotiator
  • check_permissions(self, request), checks the permissions
  • check_throttles(self, request), checks the throttling
  • check_content_negotiation(self, request, force=False), checks content negotiation

2.3 Dispatch Methods

  • initial(self, request, *args, **kwargs)

Called before the handler method. This method is used to perform permissions and throttling, and to perform content negotiation.

  • handle_exception(self, exc)

Any exception thrown by a handler method will be passed to this method, which returns a response instance, or raises an exception.

  • initialize_request(self, request, *args, **kwargs)

Ensures that the request object passed to the handler method is an instance of request, rather than Django’s HttpRequest.

  • finalize_response(self, request, response, *args, **kwargs)

Ensures that any object returned by a response handler method is rendered to the correct content type.

3. GenericAPIView

  • queryset

Used to return a collection of query objects; the get_queryset() method can also be used.

  • serializer_class

The serializer class, which should be used to validate and deserialize input, and to serialize output. Usually you must set this attribute, or override the get_serializer_class() method.

  • lookup_field, the model field that should be used to look up an individual model instance
  • lookup_url_kwarg, the URL keyword argument that should be used for object lookup
  • pagination_class

The pagination class used to return a paginated list view; by default it is the same as the DEFAULT_PAGINATION_CLASS value set in settings, and the page size can be set via rest_framework.pagination.PageNumberPagination
Filter attributes.

  • filter_backends, the list of classes that filter the queryset, the same as setting DEFAULT_FILTER_BACKENDS in settings

3.2 Basic Methods

  • get_queryset(), returns the queryset
  • get_object(), gets a specific Model instance object

The following methods are provided by the mixins classes and offer simple behavior overrides for saving and deleting objects:

  • perform_create(self, serializer), called when CreateModelMixin saves an object
  • perform_update(self, serializer), called when UpdateModelMixin updates an object
  • perform_destroy(self, instance), called when DestoryModelMixin deletes an object

4 ModelViewSet

GenericViewSet inherits from GenericAPIView. ModelViewSet, in turn, is a combination of GenericViewSet and a large number of mixins.

rest_framework/viewsets.py defines the ModelViewSet class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class ModelViewSet(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.UpdateModelMixin,
                   mixins.DestroyModelMixin,
                   mixins.ListModelMixin,
                   GenericViewSet):
    """
    A viewset that provides default `create()`, `retrieve()`, `update()`,
    `partial_update()`, `destroy()` and `list()` actions.
    """
    pass

In practice, you usually need to inherit from ModelViewSet to implement your own business logic:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class YourViewSet(viewsets.ModelViewSet):
	def list(self, request):
	    pass
	def create(self, request):
	    pass
	def retrieve(self, request, pk=None):
	    pass
	def update(self, request, pk=None):
	    pass
	def partial_update(self, request, pk=None):
	    pass
	def destroy(self, request, pk=None):
	    pass

Below is the mapping between frontend URL requests and ModelViewSet methods:

  • list(), GET method, /date-list/
  • create(), POST, /date-list/
  • retrieve(), GET, /date-list/<id>/
  • update(), PUT, /date-list/<id>/
  • partial_update(), PATCH, /date-list/<id>/
  • destroy(), DELETE, /date-list/<id>/

微信公众号
WRITTEN BY
微信公众号