Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Serializer and ModelSerializer

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly shows you "how to use Serializer and ModelSerializer", the content is easy to understand, clear, hope to help you solve your doubts, let the editor lead you to study and learn "how to use Serializer and ModelSerializer" this article.

Analysis of the result returned by Django REST Framework API

After learning the previous article, we know how to use the Django REST framework framework to design API, and I also used Schools APP to design an API

In addition, we can also look at the OPTIONS of API, and then we can get a lot of information, for example, the first line of request line 'HTTP 200 OK', indicates that the request was successful, the second line of Allow indicates the allowed request method, and the Content-Type:application/json represents the data type of entity data sent by the sender.

There is also the following json data. Name represents the interface name, description detailed description, and renders represents parsable form. Parses is the three ways that can be parsed on the server side.

We can also add comments to the API in the views.py class of app, such as the interface description to the front-end staff, and the comments can be displayed on the Django REST Framework page.

Class AllSchoolsView (APIView): "" this is the result returned by AllSchoolsView "" def get (self, request): schools = School.objects.all () schools_serializer = SchoolSerializer (schools, many=True) return Response (schools_serializer.data)

Then rerun the project, then refresh the page, and we can get the effect shown in the figure:

Login of Django REST Framework

First of all, in order to avoid logging into the Times' CSRFCheck' object has no attribute 'process_request', in Django REST Framework, we need to upgrade Django to version 1.11.6 and above: pip install django==1.11.6, remember to have two equal signs. The user can then log in successfully using the superuser created earlier

Restful API's method

GET (SELECT): fetch resources from the server (one or more)

POST (CREATE): create a new resource on the server

PUT (UPDATE): update the resource on the server (the client provides the full resource after the change)

PATCH (UPDATE): update resources on the server (client provides changed properties)

DELETE (DELETE): delete resources from the server

HEAD: get the metadata of a resource

OPTIONS: get information about which properties of the resource can be changed by the client

Implement the POST interface

First, edit the serializer.py file and correspond the fields in the SchoolSerializer class to the fields in the School table one by one to ensure that the database will not report errors in writing.

From rest_framework import serializersfrom .models import Schoolclass SchoolSerializer (serializers.Serializer): name = serializers.CharField () desc = serializers.CharField () location = serializers.CharField () create_time = serializers.DateTimeField (default=datetime.now,) course_numbers = serializers.IntegerField () def create (self, validated_data): "" Create and return a new `Snippet` instance, given the validated data. "" Return School.objects.create (* * validated_data)

Then edit the views.py file, modify the AllSchoolsView class, add a post submission method, and put a breakpoint in the code

From rest_framework.views import APIViewfrom .serializer import SchoolSerializerfrom rest_framework.response import Responsefrom rest_framework import statusclass AllSchoolsView (APIView): "this is the returned result of AllSchoolsView" def get (self, request): schools = School.objects.all () schools_serializer = SchoolSerializer (schools, many=True) return Response (schools_serializer.data) def post (self) Request): # validate the request.data data # request.data will get the field serializer = SchoolSerializer (data=request.data) submitted by post # if the verification field is legal if serializer.is_valid (): # save it directly to the database The create method serializer.save () return Response (serializer.data, status=status.HTTP_201_CREATED) return Response (serializer.errors, status=status.HTTP_400_BAD_REQUEST) of GoodsSerializer will be called here.

Then you can use postman to submit the request. Select the submission method of x-www-form-urlencoded in Body, and then fill in the values of the corresponding fields.

Then send send, encapsulate and serialize the obtained data in the post method, return it to the serialized object serializer, and finally save it to the database through the save method. Then we visit http://127.0.0.1:12345/school/all/. Is there a new record added to the obtained data?

You can also make a post request directly in the browser page. First select the submission format, then create the corresponding data, and click POST directly. If HTTP 201 Created is returned, the data has been created and written into the database.

The above is all the content of the article "how to use Serializer and ModelSerializer". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report