Django ViewSet 和Router序列化
2018-09-14 本文已影响31人
whong736
目的:学习记录rest_framework 使用ViewSet和Touter序列化,以获得商品的列表序列化为例子。达到的效果:
image.png1. 编写Model,商品的model
# -*- coding:UTF-8 -*-
from datetime import datetime
from django.db import models
# Create your models here.
from extra_apps.DjangoUeditor.models import UEditorField
class GoodsCategory(models.Model):
"""
商品类别,使用一个model完成呢个所有级联的类别,一张表表示所有的类
"""
CATEGORY_TYPE = (
(1, "一级类目"),
(2, "二级类目"),
(3, "三级类目"),
)
name = models.CharField(default="", max_length=30, verbose_name="类别名", help_text="类别名")
code = models.CharField(default="", max_length=30, verbose_name="类别code", help_text="类别code")
desc = models.TextField(default="", verbose_name="类别描述", help_text="类别描述")
# 什么级别的类
category_type = models.IntegerField(choices=CATEGORY_TYPE, verbose_name="类目级别", help_text="类目级别")
# 父类级别,使用self获得当前的model
parent_category = models.ForeignKey("self", null=True, blank=True, verbose_name="父类目级别", help_text="父目录",
related_name="sub_cat", on_delete=models.CASCADE,)
# 是否要放到导航中
is_tab = models.BooleanField(default=False, verbose_name="是否导航", help_text="是否导航")
add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间")
class Meta:
verbose_name = "商品类别"
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class GoodsCategoryBrand(models.Model):
"""
品牌名,一级类别下面的商家
"""
category = models.ForeignKey(GoodsCategory, related_name='brands', on_delete=models.CASCADE, null=True, blank=True, verbose_name="商品类目")
name = models.CharField(default="", max_length=30, verbose_name="品牌名", help_text="品牌名")
desc = models.TextField(default="", max_length=200, verbose_name="品牌描述", help_text="品牌描述")
image = models.ImageField(max_length=200, upload_to="brands/")
add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间")
class Meta:
verbose_name = "品牌"
verbose_name_plural = verbose_name
db_table = "goods_goodsbrand"
def __str__(self):
return self.name
class Goods(models.Model):
"""
商品
"""
category = models.ForeignKey(GoodsCategory, verbose_name="商品类目", on_delete=models.CASCADE, related_name='goods_cate')
goods_sn = models.CharField(max_length=50, default="", verbose_name="商品唯一货号")
name = models.CharField(max_length=100, verbose_name="商品名")
click_num = models.IntegerField(default=0, verbose_name="点击数")
sold_num = models.IntegerField(default=0, verbose_name="商品销售量")
fav_num = models.IntegerField(default=0, verbose_name="收藏数")
goods_num = models.IntegerField(default=0, verbose_name="库存数")
market_price = models.FloatField(default=0, verbose_name="市场价格")
shop_price = models.FloatField(default=0, verbose_name="本店价格")
goods_brief = models.TextField(max_length=500, verbose_name="商品简短描述")
# 商品的详细页面的描述。这里使用的是富文本的知识
goods_desc = UEditorField(verbose_name=u"内容", imagePath="goods/images/", width=1000, height=300,
filePath="goods/files/", default='')
ship_free = models.BooleanField(default=True, verbose_name="是否承担运费")
# 商品封面图片
goods_front_image = models.ImageField(upload_to="goods/images/", null=True, blank=True, verbose_name="封面图")
is_new = models.BooleanField(default=False, verbose_name="是否新品")
is_hot = models.BooleanField(default=False, verbose_name="是否热销")
add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间")
class Meta:
verbose_name = '商品'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class GoodsImage(models.Model):
"""
商品轮播图
"""
goods = models.ForeignKey(Goods, verbose_name="商品", related_name="images", on_delete=models.CASCADE,)
image = models.ImageField(upload_to="", verbose_name="图片", null=True, blank=True)
add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间")
class Meta:
verbose_name = '商品图片'
verbose_name_plural = verbose_name
def __str__(self):
return self.goods.name
# 商品的广告位
class IndexAd(models.Model):
category = models.ForeignKey(GoodsCategory, related_name='category', verbose_name="商品类目", on_delete=models.CASCADE,)
goods = models.ForeignKey(Goods, related_name='goods', on_delete=models.CASCADE,)
class Meta:
verbose_name = '首页商品类别广告'
verbose_name_plural = verbose_name
def __str__(self):
return self.goods.name
class Banner(models.Model):
"""
主页轮播的商品
"""
goods = models.ForeignKey(Goods, verbose_name="商品", on_delete=models.CASCADE,)
image = models.ImageField(upload_to='banner', verbose_name="轮播图片")
index = models.IntegerField(default=0, verbose_name="轮播顺序")
add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间")
class Meta:
verbose_name = '轮播商品'
verbose_name_plural = verbose_name
def __str__(self):
return self.goods.name
class HotSearchWords(models.Model):
"""
热搜词
"""
keywords = models.CharField(default="", max_length=20, verbose_name="热搜词")
index = models.IntegerField(default=0, verbose_name="排序")
add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间")
class Meta:
verbose_name = '热搜词'
verbose_name_plural = verbose_name
def __str__(self):
return self.keywords
image.png
2.新建serializers文件并编写对应model的serializers
# -*- coding:UTF-8 -*-
from django.db.models import Q
from rest_framework import serializers
from apps.goods.models import Goods, GoodsCategory, GoodsImage, GoodsCategoryBrand, HotSearchWords, IndexAd
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = GoodsCategory
fields = "__all__"
class GoodsImageSerializer(serializers.ModelSerializer):
class Meta:
model = GoodsImage
fields = ('image',)
class GoodsSerializer(serializers.ModelSerializer):
#覆盖外键字段
category = CategorySerializer()
images = GoodsImageSerializer(many=True)
class Meta:
model = Goods
fields = '__all__'
image.png
3.比那些view,详细了解ViewSet,重点了解使用viewsets.GenericViewSet、mixins.ListModelMixin
# -*- coding:UTF-8 -*-
from .serializer import GoodsSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from rest_framework import generics, mixins, viewsets
from apps.goods.models import Goods
from apps.goods.serializer import GoodsSerializer, CategorySerializer
from rest_framework_extensions.cache.mixins import CacheResponseMixin
class GoodsPagination(PageNumberPagination):
"""
配置分页
"""
page_size = 20
page_size_query_param = "p"
max_page_size = 100
class GoodsListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
"""
获取商品列表
"""
queryset = Goods.objects.all()
serializer_class = GoodsSerializer
pagination_class = GoodsPagination
image.png
4.项目中配置url
image.png"""MyShop02 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from rest_framework.authtoken import views
from rest_framework.documentation import include_docs_urls
from rest_framework.routers import DefaultRouter
from rest_framework_jwt.views import obtain_jwt_token
from MyShop02.settings import MEDIA_ROOT
from django.views.static import serve
from extra_apps import xadmin
from rest_framework.documentation import include_docs_urls
from rest_framework.routers import DefaultRouter
from goods.views import GoodsListViewSet
router = DefaultRouter()
router.register(r'goods', GoodsListViewSet)
urlpatterns = [
url(r'^xadmin/', xadmin.site.urls),
url(r'^media/(?P<path>.*)$', serve, {'document_root': MEDIA_ROOT}),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^', include(router.urls)),
]
5.浏览器访问链接地址
image.png觉得文章有用,请用支付宝扫描,领取一下红包!打赏一下
支付宝红包码