先說一下傳統的先後端分離,,python
class GoodsListView(View): def get(self, request): """ 經過django的view實現商品列表頁 :param request: :return: """ json_list = [] goods = Goods.objects.all()[:10] for good in goods: json_dict = {} json_dict["name"] = good.name json_dict["category"] = good.category.name json_dict["market_price"] = good.market_price json_dict["add_time"] = good.add_time json_list.append(json_dict)
#導入HttpResponse, JsonResponse 模塊 #導入json import json from django.http import HttpResponse, JsonResponse return HttpResponse(json.dumps(json_list),content_type="application")
爲了方便試,瀏覽器安裝json,vive,顯示效果更好,以上的方法痛點不少:不能對tim序例化,手工填充對象,相似於下面的步聚太多,容易出錯git
json_dict["category"] = good.category.name
json_dict["market_price"] = good.market_price
json_dict["add_time"] = good.add_timegithub
咱們使用 django自帶的 model_to_dict 來作這種json 咱們不須要手工序例化數據,方便一些django
將對象轉成json:json
goods = Goods.objects.all()[:10]
from django .forms.models import model_to_dict
for good in goods:
json_dict = model_to_dict(good)
json_list.append(json_dict)
from django.http import HttpResponse, JsonResponse後端
return HttpResponse(json.dumps(json_list),content_type="application")
只是沒有手工初始數據而己,總數據要循環,而後追加,仍然不能序例化
最後一個超級變態方法,不要初始,不要循環,serializera的方法
from .models import Goods
from django.views.generic.base import View
class GoodsListView(View):
def get(self,request):
json_list=[]
goods = Goods.objects.all()[:10]
# for good in goods:
# json_dict = {}
# json_dict["name"]=good.name
# json_dict['category'] = good.category.name
# json_dict["maret_price"]=good.market_price
# json_list.append(json_dict)
#
# from django .forms.models import model_to_dict
# for good in goods:
# json_dict = model_to_dict(good)
# json_list.append(json_dict) // 帶*這些都不須要
from django.core import serializers
import json
json_data = serializers.serialize("json",goods)
from django.http import HttpResponse
import json
return HttpResponse(json.dumps(json_data), content_type="application")
可是也要指定類型,咱們用專用的jsonResponse更方便,,,
........................完整代碼以下:由於是例子,導入包是是現用現導,方便學習:
class GoodsListView(View): def get(self, request): json_list = [] goods = Goods.objects.all()[:10] from django.forms.models import model_to_dict for good in goods: json_dict = model_to_dict(good) json_list.append(json_dict) import json from django.core import serializers json_data = serializers.serialize('json', goods) json_data = json.loads(json_data) from django.http import HttpResponse, JsonResponse return JsonResponse(json_data, safe=False)
熱身完畢,framework api 教程正式開始api
framework 簡稱爲 rest 瀏覽器
安裝必要的組件:app
詳情能夠查看官網框架
這兒共須要三步,第一新建訪問路由
第二,新建驗證,規格,序列化文件,似於原生的form
第三步,vies視圖數
路由頁面:
from rest_framework.documentation import include_docs_urls
from django.urls import path,include
from goods.views import GoodsListView
import xadmin
urlpatterns = [
path('xadmin/', xadmin.site.urls), #後臺地址
path('docs/',include_docs_urls(title = "bxy")), #自動生成文檔須要
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),#框架內部使用
path("goods/",GoodsListView.as_view(),name = "goods-list"),#用戶視圖
]
2,在 當前的app 中新建一個serializer.py 相似於原生form,驗證使用:
from rest_framework import serializers
#這兒和原生的form 沒有區別,只是多了一個關健字
class GoodsSerializer(serializers.Serializer):
name = serializers.CharField(max_length=100, required=True)
click_num = serializers.IntegerField(default=0)
3:視圖函數部份
from .serializer import GoodsSerializer #導入驗證模塊
from rest_framework.views import APIView #導入視圖模塊
from rest_framework.response import Response #渲染模塊
from .models import Goods
class GoodsListView(APIView):
def get(self,request,format = None):
goods = Goods.objects.all()[:10]
goods_serializer = GoodsSerializer(goods,many = True)
return Response(goods_serializer.data)
以上serializer 方法,須要定義很字段屬性,有沒有像modelform 同樣有提供自動的方法呢,只需6步就能所有定完字段
如查是關聯有外健的表怎麼查呢:能夠分別定義,而後在主健那表,單獨自定義必定字段用於記錄:
from rest_framework import serializers #導入serializers包
from goods.models import Goods, GoodsCategory #導入模型庫
class CategorySerializer(serializers.ModelSerializer): #定義一個類放的是外健那個表的數據據
class Meta:
model = GoodsCategory #獲得模型庫的數據
fields = "__all__"
class GoodsSerializer(serializers.ModelSerializer): #定義一個類,主健 category = CategorySerializer() # 獲得外健那個類,保存在一個字段 class Meta: model = Goods #獲得模型庫GOODs的數據 # fields = ('name', 'click_num', 'market_price', 'add_time') fields = "__all__" #獲得全部 字段