目的
序列化models数据库,达到API返回数据的效果
具体步骤:
- 安装
pip install djangorestframework
- 配置settings.py
INSTALLED_APPS = [
...
'rest_framework',
]
- 添加serializers.py
# 此文件的做用等同于forms的作用,而序列化数据库数据forms是不具备的。
from rest_framework import serializers
from main_app import models
class EnvSerializer(serializers.ModelSerializer):
class Meta:
model=models.SettingsModel
fields = "__all__"
- view中使用
from rest_framework.views import APIView
from rest_framework.response import Response # 效果等同于JsonResponse
class GetEnvs(APIView):
def get(self,request):
try:
env_obj = models.SettingsModel.objects.all()
ser = main_app_serializers.EnvSerializer(instance=env_obj,many=True)
return Response({"code":200,"data":ser.data}) #必须调用data方法
except:
return Response({"code":500,"msg":"获取失败"})