premise
This article is modified on the basis of existing projects
https://blog.csdn.net/qq_38122800/article/details/128583379?spm=1001.2014.3001.5502
1. Configure the serializer
The serializer includes two processes of serialization and deserialization. The simple understanding is
Serialization : Change the data checked from the database into json data acceptable to the front-end page.
Deserialization : Change the data passed in from the front-end into model data, which is usually used for data verification at the back-end. This article does not involve this part.
Create a new serializers.py file under DjangoProject2 (the file name is random)
code:
from demo.models import Person #导入数据表模型
from rest_framework import serializers
class PersonModelSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = "__all__"
2. Install Django Rest Framework
Execute command in terminal
pip3 install djangorestframework
Then go to the settings.py file to modify INSTALLED_APPS and configure rest_framework
code:
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"rest_framework", #Django-Rest Framework是以Django扩展应用的方式提供的
"demo"
]
3. Realize the interface function
With the same interface, the function of inserting data is realized through post access , and the function of querying data is realized through get access
Open the view.py file
import module
from rest_framework.views import APIView #视图
from rest_framework.response import Response #响应
from demo.models import Person #数据表模型
from djangoProject2.serializers import PersonModelSerializer #序列化器
from rest_framework import status #接口状态码
Define the functionality implemented by the interface
Create a new class that inherits from APIView
Let me explain here that when inserting data, use create to insert data
obj= Person.objects.create(first_name = first_name,last_name = last_name)
However, this usage needs to specify the corresponding value of each field, so update_or_create() is used. This method can directly write the entire json string after defaults. Specific usage:
update_or_create(defaults=None, **kwargs)
执行规则: filter kwargs,create/update defaults
返回值为元组: (object, created),object为新建或者更新的对象,created为一个布尔值,表示是新建还是更新,True为新建
Interface code:
class RecordList(APIView):
res = {
'code': status.HTTP_200_OK,
'data':None,
'msg': 'success',
}
#通过post请求时,实现插入数据的功能
def post(self,request):
#获取前端传入的请求体数据
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
data = {
'first_name':first_name,
'last_name': last_name,
}
print("data>>>>>>",data)
#update_or_create需要提供一个查询参数,先查询,如果不存在,则插入,如果存在,则更新。这里设置id为None,可以达到直接插入的效果
obj,iscreated= Person.objects.update_or_create(defaults=data,id=None)
print("插入结果>>>>>>>",obj)
return Response(self.res)
#通过get请求时,实现查询数据库并返回给接口的功能
def get(self,request):
#获取接口传入的数据
first_name = request.GET.get('first_name')
#根据first_name查询数据库
data_obj = Person.objects.filter(first_name=first_name)
#data_obj>>>>>> <class 'django.db.models.query.QuerySet'> <QuerySet [<Person: Person object (5)>]>
print('data_obj>>>>>>',type(data_obj),data_obj)
#实例化序列器
ser = PersonModelSerializer(instance=data_obj,many = True)
#获取序列化后的数据
self.res['data'] = ser.data
# 将数据返给接口
return Response(self.res)
#删除数据
def delete(self, request):
first_name = request.GET.get('first_name')
obj = Person.objects.filter(first_name = first_name).delete()
self.res['data'] = obj
return Response(self.res)
4. Configure routing
Configure routing in the demo/urls.py file to correspond to the interface function written in step 3
code:
urlpatterns = [
path("recordlist",views.RecordList.as_view). #接口地址:127.0.0.1:8000/st/recordlist
]
5. Use the postman request interface to verify the effect
insert data
First_name and last_name are added to the form, and the interface returns code200, indicating that the interface access is successful
Curl content, copied to posrman available
curl --location --request POST 'http://127.0.0.1:8000/st/recordlist' \
--form 'first_name="f"' \
--form 'last_name="l1234"'
Enter the database, you can see the inserted data
Query data
The interface is still: http://127.0.0.1:8000/st/recordlist
Access method: get
adds first_name as f in the parameter, to query the data in the database whose first_name is f, you can see that the interface returns all the queried data
Curl content, copied to posrman available
curl --location --request GET 'http://127.0.0.1:8000/st/recordlist?first_name=f'