一、resful api:
https://www.runoob.com/w3cnote/restful-architecture.html
二、jsonview和Vue.js插件
:https://www.cnblogs.com/whycxb/p/7126116.html
:https://www.cnblogs.com/alice-fee/p/8038367.html
三、定义视图函数:
1、基本序列化方法
class GoodsListView(View):#rul的关键字获取/获取数据
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_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.http import HttpResponse
import json
return HttpResponse(json.dumps(json_list),content_type="application/json")#json格式,但是时间等不可以序列化
#dump会报错???
'''
2、使用serializers
// data_time等字段无法序列化用serializers
goods = Goods.objects.all()[:10]
import json
from django.core import serializers
json_data = serializers.serialize('json', goods)
json_data = json.load(json_data)
from django.http import HttpResponse, JsonResponse
return JsonResponse(json_data,safe=False)#
data_time等字段无法序列化报错Object of type ‘ImageFieldFile’ is not JSON serializable
3、使用Django REST framework:https://www.w3cschool.cn/lxraw/lxraw-pdz435oa.html
setting中配置:‘rest_framework’
rul中配置:from rest_framework.documentation import include_docs_urls
from django.conf.urls import url, include
url(r’goods/$’, GoodsListView.as_view(), name=“goods_list”),
url(r’^api-auth/’, include(‘rest_framework.urls’, namespace=‘rest_framework’)),
3.1实现序列化
//serializers.py
// from rest_framework import serializers解决序列化
class GoodsSerializer(serializers.Serializer):#方法一
name = serializers.CharField(required=True,max_length=100 )
click_name =serializers.IntegerField(default=0)
#通过model继承优化后
class CategorySerializer(serializers.ModelSerializer):#继承ModelSerializer
class Meta:
model = GoodsCategory#直接通过model做映射
fields = "__all__"
class GoodsSerializer(serializers.ModelSerializer):
category = CategorySerializer()
class Meta:
model = Goods
fields = "__all__"
//view.py
class GoodsListView(APIView):
def get(self, request):
goods = Goods.objects.all()[:10]
goods_serializer = GoodsSerializer(goods,many = True)
return Response(goods_serializer.data)
#通过mixins优化
class GoodsListView(mixins.ListModelMixin, generics.GenericAPIView):
queryset = Goods.objects.all()[:10]#取数据
serializer_class = GoodsSerializer#序列化
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
#省去get的方法:
class GoodsListView( generics.ListCreateAPIView):#ListCreateAPIView封装了get,若没有封装的函数则这边会报错
queryset = Goods.objects.all()[:10]#取数据
serializer_class = GoodsSerializer#序列化
3.2实现分页
1.setting里关于rest_framwork配置
REST_FRAMEWORK = {
‘PAGE_SIZE’:10,
}
或者不在setting里设置,在view.py 中单独写:
class GoodsPagination(PageNumberPagination):
page_size = 12
page_size_query_param = 'page_size'
page_query_param = "page"
max_page_size = 100
3.3router简化rul.py
from rest_framework.routers import DefaultRouter
from goods.views import GoodsListViewSet
router = DefaultRouter()
#配置goods的url
router.register(r'goods', GoodsListViewSet, basename="goods")#base_name不再使用
urlpatterns = [#正则表达式+视图函数名
url(r'^', include(router.urls)),
3.4总结
最上层GenericViewSet由GenericAPIView组成
GenericAPIView只继承APIView,实现序列化等功能打包
GenericAPIView和mixin的函数组合成其他功能函数就是generics,使用时可以省却get等绑定
viewsets也是将ViewSetMixin的函数和GenericAPIView组合,但绑定是在url中实现,可以自己绑定,其次有很多action,功能更多
viewsets和generics已有有现成绑定好的函数
3.5.分页,搜索,排序
#分页
from rest_framework.pagination import PageNumberPagination
from rest_framework import viewsets
#过滤
from .filters import GoodsFilter
from django_filters.rest_framework import DjangoFilterBackend
#查询
from rest_framework import filters
class GoodsListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
"""
商品列表页, 分页, 搜索, 过滤, 排序
"""
queryset = Goods.objects.all()#取数据
serializer_class = GoodsSerializer#序列化
pagination_class = GoodsPagination#分页
filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)#过滤和搜索和排序
filter_class = GoodsFilter
search_fields = ('name')#^符号表示必须要以该内容开头,=符号精确搜索,
ordering_field = ('sold_num')#升序: