(PS:转载自http://www.cnblogs.com/derek1184405959/p/8810591.html  有修改)

一、drf的过滤

(1)添加到app里面

INSTALLED_APPS = [
'django_filters',
]

(2)新建filter.py

自定义一个过滤器

# goods/filters.py

import django_filters

from .models import Goods

class GoodsFilter(django_filters.rest_framework.FilterSet):
'''
商品过滤的类
'''
#两个参数,name是要过滤的字段,lookup是执行的行为,‘小与等于本店价格’。
#注意,这里我用的django-filter是2.0.0,因此跟视频教程中不一样,所以这里的
#name="shop_price"要改为field_name="shop_price",不然报错
price_min = django_filters.NumberFilter(name="shop_price", lookup_expr='gte')
price_max = django_filters.NumberFilter(name="shop_price", lookup_expr='lte') class Meta:
model = Goods
fields = ['price_min', 'price_max']

(3)views.py

from .filters import GoodsFilter
from django_filters.rest_framework import DjangoFilterBackend class GoodsListViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
'商品列表页' #这里必须要定义一个默认的排序,否则会报错
queryset = Goods.objects.all().order_by('id')
# 分页
pagination_class = GoodsPagination
serializer_class = GoodsSerializer
filter_backends = (DjangoFilterBackend,) # 设置filter的类为我们自定义的类
filter_class = GoodsFilter

二、drf的搜索和排序

添加搜索功能

搜索的字段可以使用正则表达式,更加的灵活

class GoodsListViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
'商品列表页' #这里必须要定义一个默认的排序,否则会报错
queryset = Goods.objects.all().order_by('id')
# 分页
pagination_class = GoodsPagination
serializer_class = GoodsSerializer
filter_backends = (DjangoFilterBackend,filters.SearchFilter) # 设置filter的类为我们自定义的类
filter_class = GoodsFilter
#搜索,=name表示精确搜索,也可以使用各种正则表达式
search_fields = ('=name','goods_brief')

添加排序功能

class GoodsListViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
'商品列表页' #这里必须要定义一个默认的排序,否则会报错
queryset = Goods.objects.all()
# 分页
pagination_class = GoodsPagination
#序列化
serializer_class = GoodsSerializer
filter_backends = (DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter) # 设置filter的类为我们自定义的类
#过滤
filter_class = GoodsFilter
#搜索,=name表示精确搜索,也可以使用各种正则表达式
search_fields = ('=name','goods_brief')
#排序
ordering_fields = ('sold_num', 'add_time')

三、商品类别数据显示

1、商品类别数据接口

(1)商品分类有两个接口:

一种是全部分类:一级二级三级

一种是某一类的分类以及商品详细信息("CategoryViewSet"继承"mixins.RetrieveModelMixin"):

开始写商品分类的接口

(2)序列化

给分类添加三级分类的serializer

goods/serializers.py

from rest_framework import serializers
from .models import Goods,GoodsCategory class CategorySerializer3(serializers.ModelSerializer):
'''三级分类'''
class Meta:
model = GoodsCategory
fields = "__all__" class CategorySerializer2(serializers.ModelSerializer):
'''
二级分类
'''
#在parent_category字段中定义的related_name="sub_cat"
sub_cat = CategorySerializer3(many=True)
class Meta:
model = GoodsCategory
fields = "__all__" class CategorySerializer(serializers.ModelSerializer):
"""
商品一级类别序列化
"""
sub_cat = CategorySerializer2(many=True) # “many=True”表示不止一个二级分类
class Meta:
model = GoodsCategory
fields = "__all__"

(3)views.py

class CategoryViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
'''
list:
商品分类列表数据
''' queryset = GoodsCategory.objects.filter(category_type=1)
serializer_class = CategorySerializer

说明:

  • 注释的内容,在后面生成drf文档的时候会显示出来,所有要写清楚
  • 要想获取某一个商品的详情的时候,继承 mixins.RetrieveModelMixin  就可以了(本来按照以前的做法,获取详情页需要我们配置url,以便获取某个商品id,但这些viewsets.GenericViewSet已经
  • 替我们完成了,不需要我们自己动手写代码)

(4)url配置

# 配置Category的url
router.register(r'categorys', CategoryViewSet, base_name="categorys")

2、vue展示商品分类数据

接口相关代码都放在src/api/api.js里面,调试接口的时候我们首先需要新建一个自己的host,然后替换要调试的host

(1)新建local_host

let local_host = 'http://127.0.0.1:8000'

(2)替换商品类别默认的host

//获取商品类别信息
export const getCategory = params => {
if('id' in params){
return axios.get(`${local_host}/categorys/`+params.id+'/');
}
else {
return axios.get(`${local_host}/categorys/`, params);
}
};

这个时候访问 http://127.0.0.1:8080/#/app/home/index

发现不显示商品分类了,是因为这涉及到了跨域问题,接下来就解决跨域的问题

(前端端口是8080,后端接口是8000,端口不同导致了跨域问题)

drf跨域问题

后端服务器解决跨域问题的方法

(1)安装模块

pip install django-cors-headers

django-cors-headers 使用说明:https://github.com/ottoyiu/django-cors-headers

(2)添加到INSTALL_APPS中

INSTALLED_APPS = (
... 'coreschema', ... )

(3)添加中间件

下面添加中间件的说明:

CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django's CommonMiddleware or Whitenoise's WhiteNoiseMiddleware. If it is not before, it will not be able to add the CORS headers to these responses.

Also if you are using CORS_REPLACE_HTTPS_REFERER it should be placed before Django's CsrfViewMiddleware (see more below).

意思就是 要放的尽可能靠前,必须在CsrfViewMiddleware之前。我们直接放在第一个位置就好了

MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

(4)设置为True

CORS_ORIGIN_ALLOW_ALL = True

现在再访问 http://127.0.0.1:8080/#/app/home/index   数据就可以填充进来了

在一级分类中设置为True

3、vue展示商品列表页数据

这里我们点击“tab”栏进行搜索和点击“热门关键词”进行搜索,左侧列表栏显示的数据是不一样的。点击“tab”栏,左侧显示的是一级和二级列表,点击“热门关键词”进行搜索,左侧显示的是三级的列表信息。那么是如何做到这点的呢??主要还是在前端,不同的方式搜索,虽然用的是同一个组件,但是所附加的参数不同,这样就区别开来了。

商品列表页会判断我们是serach还是getGoods

getListData() {
if(this.pageType=='search'){
getGoods({
search: this.searchWord, //搜索关键词
}).then((response)=> {
this.listData = response.data.results;
this.proNum = response.data.count;
}).catch(function (error) {
console.log(error);
});
}else {
getGoods({
page: this.curPage, //当前页码
top_category: this.top_category, //商品类型
ordering: this.ordering, //排序类型
pricemin: this.pricemin, //价格最低 默认为‘’ 即为不选价格区间
pricemax: this.pricemax // 价格最高 默认为‘’
}).then((response)=> { this.listData = response.data.results;
this.proNum = response.data.count;
}).catch(function (error) {
console.log(error);
});
} },

说明:

(1)page分页

page_size数量与前端一致

页码参数与起前端一致"page"

class GoodsPagination(PageNumberPagination):
'''
商品列表自定义分页
'''
#默认每页显示的个数
page_size = 12
#可以动态改变每页显示的个数
page_size_query_param = 'page_size'
#页码参数
page_query_param = 'page'
#最多能显示多少页
max_page_size = 100

(2)过滤

top_category是商品的一级分类,需要传入参数:一级分类的id

pricemin和pricemax与前端保持一致

获取一级分类下的所有商品

# goods/filters.py

import django_filters

from .models import Goods
from django.db.models import Q class GoodsFilter(django_filters.rest_framework.FilterSet):
'''
商品过滤的类
'''
#两个参数,name是要过滤的字段,lookup是执行的行为,‘小与等于本店价格’
pricemin = django_filters.NumberFilter(name="shop_price", lookup_expr='gte')
pricemax = django_filters.NumberFilter(name="shop_price", lookup_expr='lte')
top_category = django_filters.NumberFilter(name="category", method='top_category_filter')
  # 自定义我们想要的过滤逻辑
def top_category_filter(self, queryset, name, value):
# 不管当前点击的是一级分类二级分类还是三级分类,都能找到。
return queryset.filter(Q(category_id=value) | Q(category__parent_category_id=value) | Q(
category__parent_category__parent_category_id=value)) class Meta:
model = Goods
fields = ['pricemin', 'pricemax']

(3)排序

  GoodsListViewSet中ording与前端要一致

 #排序
ordering_fields = ('sold_num', 'shop_price')

(4)替换为local_host

//获取商品列表
export const getGoods = params => { return axios.get(`${local_host}/goods/`, { params: params }) }

(5)搜索

#搜索
search_fields = ('name', 'goods_brief', 'goods_desc')

现在就可以从后台获取商品的数据了,主要功能

  • 分类过滤
  • 价格区间过滤
  • 显示商品数量
  • 分页
  • 搜索

Django REST framework+Vue 打造生鲜电商项目(笔记三)的更多相关文章

  1. Django REST framework+Vue 打造生鲜电商项目(笔记二)

    (转自https://www.cnblogs.com/derek1184405959/p/8768059.html)(有修改) 接下来开始引入django resfulframework,体现它的强大 ...

  2. Django REST framework+Vue 打造生鲜电商项目(笔记四)

    (PS:部分代码和图片来自博客:http://www.cnblogs.com/derek1184405959/p/8813641.html.有增删) 一.用户登录和手机注册 1.drf的token功能 ...

  3. Django REST framework+Vue 打造生鲜电商项目(笔记十)

    (from:https://www.cnblogs.com/derek1184405959/p/8877643.html  有修改) 十三.首页.商品数量.缓存和限速功能开发 首先把pycharm环境 ...

  4. Django REST framework+Vue 打造生鲜电商项目(笔记九)

    (from:http://www.cnblogs.com/derek1184405959/p/8859309.html) 十二.支付宝沙箱环境配置 12.1.创建应用 进入蚂蚁金服开放平台(https ...

  5. Django REST framework+Vue 打造生鲜电商项目(笔记十一)

    (form: http://www.cnblogs.com/derek1184405959/p/8886796.html 有修改) 十四.social_django 集成第三方登录 1.申请应用 进入 ...

  6. Django REST framework+Vue 打造生鲜电商项目(笔记八)

    (form:http://www.cnblogs.com/derek1184405959/p/8862569.html) 十一.pycharm 远程代码调试 第三方登录和支付,都需要有服务器才行(回调 ...

  7. Django REST framework+Vue 打造生鲜电商项目(笔记七)

    十.购物车.订单管理和支付功能 1.添加商品到购物车 (1)trade/serializer.py 这里的serializer不继承ModelSerializer,是因为自己写的Serializer更 ...

  8. Django REST framework+Vue 打造生鲜电商项目(笔记一)

    首先,这系列随笔是我个人在学习Bobby老师的Django实战项目中,记录的觉得对自己来说比较重要的知识点,不是完完整整的项目步骤过程....如果有小伙伴想找完整的教程,可以看看这个(https:// ...

  9. Django REST framework+Vue 打造生鲜电商项目(笔记六)

    (部分代码来自https://www.cnblogs.com/derek1184405959/p/8836205.html) 九.个人中心功能开发 1.drf的api文档自动生成 (1) url #d ...

随机推荐

  1. Beginning Linux Programming 学习--chapter 17 Programming KDE using QT

    KDE: KDE,K桌面环境(K Desktop Environment)的缩写.一种著名的运行于 Linux.Unix 以及FreeBSD 等操作系统上的自由图形桌面环境,整个系统采用的都是 Tro ...

  2. Springmvc在项目启动时查询数据库并初始化静态变量

    private static List<ResourceEntity> resourceList = null; //初始化的全局静态变量 @Autowired private Resou ...

  3. Word 下划线无法对齐?用表格替代下划线(论文封面必备)

    1. 前言 在使用Word排版制作合同或者论文封面时,我们可能会使用一些下划线,但是,你在下划线上输入内容后,发现下划线会随着内容而增长,根本无法与上下的下划线对齐.有什么好办法可以解决这一问题呢?其 ...

  4. Python--递归函数实现:多维嵌套字典数据无限遍历

    原创:多层嵌套字典无限遍历,实现当value值以特殊字符$开头,并且等于某项值时,用随机函数替换该参数 """处理前的字典{'patient': {'avatarPic' ...

  5. oracle sqlplus命令

    show和set命令是两条用于维护SQL*Plus系统变量的命令 SQL> show all --查看所有68个系统变量值 SQL> show user --显示当前连接用户 SQL> ...

  6. Istio最佳实践:在K8s上通过Istio服务网格进行灰度发布

    Istio是什么? Istio是Google继Kubernetes之后的又一开源力作,主要参与的公司包括Google,IBM,Lyft等公司.它提供了完整的非侵入式的微服务治理解决方案,包含微服务的管 ...

  7. 深度学习的激活函数 :sigmoid、tanh、ReLU 、Leaky Relu、RReLU、softsign 、softplus、GELU

    深度学习的激活函数  :sigmoid.tanh.ReLU .Leaky Relu.RReLU.softsign .softplus.GELU 2019-05-06 17:56:43 wamg潇潇 阅 ...

  8. WPF GridView动态添加项并读取数据

    假设数据库有如下表, 首先我们创建一个WPF工程,界面如下 <Window x:Class="WpfApplication2.MainWindow" xmlns=" ...

  9. SSH和SSM对比异同点、各自优势

    1SSH和SSM定义SSH 通常指的是 Struts2 做控制器(Action),Spring 管理各层的组件,Hibernate 负责持久化层. SSM 则指的是 SpringMVC 做控制器(co ...

  10. bootstrap环境搭建

    Bootstrap 是stwitter公司的两名前端设计师设计的基于html css javascript的超强的前端框架. Bootstrap 是一移动设备为优先,pc机,平板,手机皆适用的框架. ...