Understanding of serializer

Source: Internet
Author: User
In fact, it is the naming style of Django restful frameworkrestful API, mainly because front-end and back-end separation occurs in front-end and back-end separation development: the user accesses the server of static files, and all the data is sent to the restful style by Ajax requests: data should be a term, and the verb is returned to the front-end by an HTTP request method to express the restful style API. No matter what Request Method

"'Features: repeated
Because no matter what request method, the object content must be returned to the front-end, which is in JSON format.
Therefore, if a query result object needs to be traversed into a dictionary every time, it is the same as flask.

If the GET request is not a request with content, the request received from the front-end is in JSON format.
Each time, you need to extract the content from the request. Body in bytes format.
Decode is decoded into a JSON string and then loads is used as a dictionary that can be processed by python.
"'

"'
Note:
Return jsonresponse (book_list, safe = false)

Safe description, the book_list we passed in is a list format. In front-end JSON, {} format is supported, and [] format is also supported. However, Django considers that the JSON format of [] is insecure and will be verified. option to disable false, []

"'

"'
Serialization: traverses the query results, converts them to a dictionary, and returns the jsonresponse
Deserialization: the front-end JSON is processed into a dictionary and then verified.
"'

"'
1. Build a DRF framework project based on Django
Install DRF: Pip install djangorestframework
Register DRF: installed_apps = ['rest _ framework',]
Create a serializers. py in the sub-application to execute serialization and deserialization.
In Views, Class View uses the serializer to write the address in URLs.
"'

"'
2. serializer

Definition: in fact, modelserializer is a subclass of serializer. It is more convenient to create a serializer with model classes. The actual serializer is as follows:
Class bookinfoserializer (serializers. serializer): Actually inherits serializer
"Book data serializer" serializer: serialization and deserialization
Id = serializers. integerfield (Label = 'id', read_only = true) read_only
Btitle = serializers. charfield (Label = 'name', max_length = 20)
Bpub_date = serializers. datefield (Label = 'publication date', required = false)
Bread = serializers. integerfield (Label = 'reading', required = false)
Bcomment = serializers. integerfield (Label = 'comments', required = false)
Image = serializers. imagefield (Label = 'image', required = false)

Field: similar to the creation of model classes. For specific fields, see handouts and common parameters (constraints)

Use: Create the object serializer = serializer (instance = none, Data = empty, ** kwarg)
Description: During serialization, model objects are passed into the instance parameter instance = serialized object.
During deserialization, the data to be deserialized is passed into the data parameter data = deserialization object.
You can use the context parameter to add additional data, that is, ** kwarg: context = {'request': Request} can be obtained through the context attribute of the serializer object.
"'

"'
3. serialization operation: the process of constructing a dictionary is traversed after an object is queried, and jsonresponse is executed by the built-in Renderer.

3-1. serialization only uses the first parameter instance of the serializer object
Serializer = bookinfoserializer (instance = book)
The serialized data can be obtained through the data attribute. This data is not the same as the second parameter.
Serializer. Data

{'Id': 2, 'btitle': 'tianlong Babu ', 'bpub _ date': '2017-07-24', 'bread': 36, 'bcomment': 40, 'image': None}

3-2. If you want to serialize a query set queryset that contains multiple pieces of data, add the Limit = true parameter.
Book_qs = bookinfo. Objects. All ()
Serializer = bookinfoserializer (book_qs, bytes = true)
Serializer. Data
"'

"'
4. nested serialization of correlated objects (hbook method adopted by hero-> book)

4-1.hbook is a foreign key: primarykeyrelatedfield
Hbook = serializers. primarykeyrelatedfield (Label = 'book', read_only = true)
Because it is a foreign key, the second location must have read_only = true or the query set queryset = bookinfo. Objects. All () does not report an error
When serializer. Data is serialized, the result is the primary key of the associated object {'hbook': 2}, that is, Book. Id.

4-2. Because the ID is not intuitive, change the foreign key field to stringrelatedfield for the detailed content string.
Hbook = serializers. stringrelatedfield (Label = 'book ')
Result: {'hbook': 'tianlong Babu '}

4-3. interface link: hyper‑relatedfield
Hbook = serializers. hyper1_relatedfield (Label = 'book', read_only = true, view_name = 'books-detail ')
You must specify the view_name parameter so that DRF can search for routes based on The View name and splice them into a complete URL. What is this view_name? One parameter in the URL is a namespace and associated with it.
Result: {'hbook': 'http: // 127.0.0.1: 8000/books/2 /'}

4-4. Associate the specified field data of the object: slugrelatedfield
Hbook = serializers. slugrelatedfield (Label = 'book', read_only = true, slug_field = 'bpub _ date ')
Slug_field specifies the field of the associated object
Result: {'hbook': datetime. Date (1986, 7, 24 )}

4-5. Use the serializer of the correlated object: serialize all contents of the book directly.
Hbook = bookinfoserializer ()
Result: {'hbook': ordereddict ([('id', 2), ('btitle', 'tianlongbabu ') te', '2017-07-24 '), ('bread', 36), ('bcomment', 40), ('image', none)])}

Understanding of serializer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.