DRF实战--展示商品列表

展示商品列表

商品分类

商品需要三层分类,所以需要三个serializer分别序列化三次自己

class GoodCategorySerializer3(serializers.ModelSerializer):
    '''
    三级分类
    '''
    class Meta:
        model = GoodCategory
        fields = "__all__" # 包含所有字段


class GoodCategorySerializer2(serializers.ModelSerializer):
    '''
    二级分类
    '''
    sub_cat = GoodCategorySerializer3(many=True)
    class Meta:
        model = GoodCategory
        fields = "__all__" # 包含所有字段

class GoodCategorySerializer(serializers.ModelSerializer):
    '''
    一级分类
    '''
    # sub_cat 是Category表中的自关联字段parent_category的relate_name,
    # 用于一对多反向引用时,点出二级分类,配置在一的那一方
    # 找出所有parent_category等于当前这个一级分类的parent_category的二级分类
    # many=True 表示会有多个
    sub_cat = GoodCategorySerializer2(many=True)
    class Meta:
        model = GoodCategory
        fields = "__all__" # 包含所有字段

然后在view中配置

class GoodsCategoryViewSet(mixins.ListModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet):
    '''
    list
        展示所有的商品类别信息,用于导航栏
    '''
    # 重要,只显示一级分类
    queryset = GoodCategory.objects.filter(category_type=1)
    serializer_class = GoodCategorySerializer

继承mixins.RetrieveModelMixin,用于获取对应Id的分类

浏览器的url

GET /category/24/


前端中设置

app.js

let localhost = 'http://127.0.0.1:8000';

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

Django服务器设置跨域

  • https://github.com/ottoyiu/django-cors-headers
  • 安装
  • 配置settings
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
CORS_ORIGIN_ALLOW_ALL = True

补充: 设置node.js中的服务器代理也可以解决跨域的问题

使用方法过滤

filters

 def top_category_filter(self,queryset,name,value):
        # category是外键 category_id找到对应的外键表的id
        # parent_category自关联的外键,
    # category__parent_category_id找到category_id找到对应的外键表的parent_category对应的表的id
        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', 'name', 'top_category']

你可能感兴趣的:(Django,Rest,Framework)