1. View Class in Django
First, recall how Django handles a request. After receiving a request, Django creates a handler of type WSGIHandler, and the handler controls the entire processing flow.
So how are the request URL and the View associated with each other?
Django first loads the URLconf according to the ROOT_URLCONF setting, then matches the URLpatterns in the URLconf one by one in order, stopping as soon as a match is found. It then calls the view function of the URLpattern with the HttpRequest object as an argument.
Now let’s look at how class-based view routing is configured:
| |
django/views/generic/base.py defines the View class:
| |
By calling the as_view() method, the returned dispatch() function is handed to the routing function.
The dispatch() function, based on the request method, calls the function in the View class with the same name as the request method.
This makes the processing logic very clear. Compared with function views, class views have an extra dispatch step, which can be understood as a second round of routing.
2. View Class in restframework
restframework inherits from Django’s View and implements three levels of View, namely APIView, GenericAPIView, and GenericViewSet. Let’s analyze them one by one below.
2.1 APIView
rest_framewor/views.py defines the APIView class:
| |
In the initial function, the API version, authentication and authorization, permission checks, and access rate are validated. At the same time, restframework wraps the request once again.
In usage, restframework’s APIView is not very different from Django’s View, but it enhances the functionality the View provides.
2.2 GenericAPIView
rest_framework/generics.py defines the GenericAPIView class:
| |
GenericAPIView inherits from APIView and adds a number of class methods:
get_queryset, gets the QuerySetget_object, gets a single recordget_serializer, gets the serialized dataget_serializer_class, gets the model class to be serializedget_serializer_context, gets the data to be serialized, defining a dictionary of some formatpaginator, the paginator
Besides implementing a View Class by inheriting directly from GenericAPIView, restframework also provides a large number of mixins. By inheriting from mixins, you can quickly compose the operations you need. See the example below:
| |
More mixins:
| mixins | Function | Corresponding HTTP request method |
|---|---|---|
| mixins.ListModelMixin | Defines the list method, returns a list from querylist | GET |
| mixins.CreateModelMixin | Defines the create method, creates an instance | POST |
| mixins.RetrieveModelMixin | Defines the retrieve method, returns a specific instance | GET |
| mixins.UpdateModelMixin | Defines the update method, updates an instance | PUT/PATCH |
| mixins.DestroyModelMixin | Defines the delete method, deletes an instance | DELETE |
2.4 GenericViewSet
GenericAPIView provides the basic operations of create, delete, update, and query, and can be used for rapid API development. But when these operations need to be combined to implement complex business logic, it may not be so convenient.
Fortunately, restframework provides GenericViewSet for handling more complex business logic.
rest_framework/viewsets.py defines the GenericAPIView class:
| |
There are 5 built-in ViewSets, namely
- ViewSetMixin
- ViewSet
- GenericViewSet
- ReadOnlyModelViewSet
- ModelViewSet
There are two ways to bind a ViewSet to a specified URL:
- Manually bind the ViewSet to a URL
In urls.py, add:
| |
This dispatches the get request method under the snippets/ path to the list function, and the post request method to the create method.
- Use the routers provided by restframework
In urls.py, add:
| |
3. Serializer
The Serializer and ModelSerializer in restframework are similar to Django’s Form and ModelForm.
3.1 Serializer
| |
- Serialization: object -> Json
| |
- Deserialization: String -> Json
| |
It can also be used for validation, to check whether the submitted data is valid:
| |
3.2 ModelSerializer
Compared with declaring field by field above, ModelSerializer can quickly build the serializer for the relevant model. It provides the following features:
- Automatically generates model-based fileds
- Automatically generates validators, such as the
unique_togethervalidator - Includes create and update methods by default
- Foreign keys are mapped to
PrimaryKeyRelatedField
| |
4. References
- http://www.ziawang.com/article/302/
- https://q1mi.github.io/Django-REST-framework-documentation/tutorial/quickstart_zh/
- https://blog.csdn.net/l_vip/article/details/79131289
- https://darkcooking.gitbooks.io/django-rest-framework-cn/content/chapter0.html
- http://www.cnblogs.com/renpingsheng/p/7892719.html
- https://whatwewant.gitbooks.io/django-rest-framework-tutorial-cn/content/1.Serialization.html
