Deserialization , Deserialization is receiving from the front end json data , The process of converting to a data object , update operation 、 The save operation has a deserialization operation , Receiving front end -> Validation data -> Save or update to a new data object
Serialization converts the obtained data object into json data .
If you use the writing method of the previous article , Both deserialization and serialization should write their own code , In order to improve efficiency , Use Django Rest Framework, The deserialization and serialization code are encapsulated , Define a serializer Serializer, Can help automate deserialization and serialization
Django REST framework With the help of Django Framework to encapsulate the serializer
Install first DjangoRESTframework Module , You can use commands
1、pip install djangorestframework , have access to pycharm Of Python Interpreter Installation
2、 When you use it , Think of it as a new application , Note that this is not a new project , Can be directly in setting.py Register in
'rest_framework',
3、 Import directly when using
from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView, RetrieveAPIView, DestroyAPIView
Directly inherit this class when using
for example
class BookCView(CreateAPIView)
Some in the CreateAPIView Source code of this class , It's found that it already has post request ,
class CreateAPIView(mixins.CreateModelMixin,
GenericAPIView):
"""
Concrete view for creating a model instance.
"""
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
Continue to click in to see create Method
class CreateModelMixin:
"""
Create a model instance.
"""
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def perform_create(self, serializer):
serializer.save()
def get_success_headers(self, data):
try:
return {'Location': str(data[api_settings.URL_FIELD_NAME])}
except (TypeError, KeyError):
return {}
From the source code, the first step is to obtain data
Then check the data
Save the data
Serialization returns data
DjangoRESTframework The serialization has been encapsulated for us 、 Deserialization , We can inherit these classes when we use them .
When you use it , Think of it as an application , Come first setting.py Register in rest_framework, Then use it from rest_framework.generics The introduction of package , Then inherit these classes .