“Apiview方式实现商品列表页2”的版本间的差异
来自CloudWiki
(创建页面,内容为“==序列化serializers.py== 基于DRF ,编写serializers 序列化功能 <nowiki> __author__ = 'bobby' from rest_framework import serializers from goods.models i…”) |
|||
(未显示同一用户的1个中间版本) | |||
第60行: | 第60行: | ||
[[文件:bd20-5-62.png|600px]] | [[文件:bd20-5-62.png|600px]] | ||
+ | |||
+ | 上图中 图片位置的补全,是DRF 根据settings.py中MEDIA_URL参数自动配置的结果。 | ||
+ | |||
+ | 另外,按下Option按钮,会显示: | ||
+ | |||
+ | <nowiki>HTTP 200 OK | ||
+ | Allow: GET, HEAD, OPTIONS | ||
+ | Content-Type: application/json | ||
+ | Vary: Accept | ||
+ | |||
+ | { | ||
+ | "name": "Goods List", | ||
+ | "description": "商品列表页", | ||
+ | "renders": [ | ||
+ | "application/json", | ||
+ | "text/html" | ||
+ | ], | ||
+ | "parses": [ | ||
+ | "application/json", | ||
+ | "application/x-www-form-urlencoded", | ||
+ | "multipart/form-data" | ||
+ | ] | ||
+ | }</nowiki> |
2020年8月2日 (日) 01:23的最新版本
序列化serializers.py
基于DRF ,编写serializers 序列化功能
__author__ = 'bobby' from rest_framework import serializers from goods.models import Goods class GoodsSerializer(serializers.ModelSerializer): class Meta: model = Goods fields = "__all__"
视图层views.py
from .serializers import GoodsSerializer from rest_framework.views import APIView from rest_framework.response import Response from .models import Goods # Create your views here. class GoodsListView(APIView): """ 商品列表页 """ def get(self, request): goods =Goods.objects.all()[:10] goods_serializer = GoodsSerializer(goods,many=True) return Response(goods_serializer.data)
路由urls.py
from django.conf.urls import url, include #from django.contrib import admin import xadmin from mxshop.settings import MEDIA_ROOT from django.views.static import serve from rest_framework.documentation import include_docs_urls from goods.views import GoodsListView urlpatterns = [ url(r'^xadmin/', xadmin.site.urls), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^media/(?P<path>.*)$', serve, {"document_root": MEDIA_ROOT}), url(r'goods/$',GoodsListView.as_view(), name="goods-list"), url(r'docs/', include_docs_urls(title="silutong")), ]
测试
在浏览器输入:http://10.0.0.30:8000/goods/
上图中 图片位置的补全,是DRF 根据settings.py中MEDIA_URL参数自动配置的结果。
另外,按下Option按钮,会显示:
HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "name": "Goods List", "description": "商品列表页", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ] }