Django 无限级分类

应用场景

`京东、淘宝`等平台,都会用到Django模型中的`自关联`

Django 无限级分类

django 后端代码展示

模型的创建

from django.db import models

# Create your models here.
class BaseModel(models.Model):
    # 创建时间
    create_time = models.DateTimeField(auto_now_add=True)
    # 更新时间
    update_time = models.DateTimeField(auto_now=True)

    class Meta:
        # 不生成表
        abstract = True

class Cate(BaseModel):
    # 种类名称
    name = models.CharField(max_length=128)
    # 继承本身  关联下一级
    parent = models.ForeignKey('self',on_delete=models.CASCADE,null=True,blank=True,related_name='son')
    # 类别
    level = models.IntegerField(blank=True)
    # 第三类别
    top_parent = models.IntegerField(null=True,blank=True)

    def __str__(self):
        return self.name
    class Meta:
        db_table = 'cart'

创建超级用户 在admin里添加数据

创建超级用户命令
python manage.py createsuperuser

admin.py

from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Cate)
serializers  序列化器

from rest_framework import serializers

from .models import *

class CartSer(serializers.ModelSerializer):

    class Meta:
        model = Cate
        fields = '__all__'

功能实现

from rest_framework.views import APIView
from rest_framework.response import Response

from .models import *
from .serializers import *

def getCate(cates):
    '''
    对分类进行解析
    '''
    dict = {}
    list = []
    for i in cates:
        dict[i['id']] = i

    for j in cates:
        parent_id = j['parent']
        if not parent_id:
            list.append(j)
        else:
            if 'son' not in dict[parent_id]:
                dict[parent_id]['son'] = []
            dict[parent_id]['son'].append(j)
    return list

class CateAPIView(APIView):

    def get(self,request):
        # 获取到全部数据
        cate_obj = Cate.objects.all()
        print(cate_obj)
        # 对数据进行序列化
        cate_ser = CartSer(cate_obj,many=True)
        # 调用上面函数的分类方法
        cate_list = getCate(cate_ser.data)
        # 返回前端需要的对象
        return Response({'code':200,'cate_list':cate_list})

子路由配置

from django.urls import path
from . import views
urlpatterns = [
    path('cate/',views.CateAPIView.as_view())
]

vue

axios下载命令
cnpm install --save axios

main.js配置全局axios

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

// 配置全局axios
import axios from 'axios'
Vue.prototype.axios=axios
axios.defaults.baseURL = 'http://127.0.0.1:8000'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

index.js

import Vue from 'vue'
import Router from 'vue-router'
import Cate from '@/components/Cate'

Vue.use(Router)

export default new Router({
  // 去除路由#号
  mode:'history',
  routes: [
    {
      path: '/cate',
      name: 'Cate',
      component: Cate
    }
  ]
})

页面展示

<template>
  <div>
    <h1>无限极分类页面</h1>
    <!-- 一级分类 -->
    <div v-for="i in cate_list" :key="i.id">
      <!-- 二级分类 -->
      <div v-for="j in i.son" :key="j.id">
        <!-- 三级分类 -->
        <div v-for="k in j.son" :key="k.id">
          <!-- 四级分类 -->
          <div v-for="a in k.son" :key="a.id">
            <!-- 五级分类 -->
            <div v-for="b in a.son" :key="b.id">
              <table align="center" cellspacing="0" border="1" width="600px">
                <tr>
                  <td>一级分类</td>
                  <td>二级分类</td>
                  <td>三级分类</td>
                  <td>四级分类</td>
                  <td>五级分类</td>
                </tr>
                <tr>
                  <td>{{ i.name }}</td>
                  <td>{{ j.name }}</td>
                  <td>{{ k.name }}</td>
                  <td>{{ a.name }}</td>
                  <td>{{ b.name }}</td>
                </tr>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cate_list: [],
    };
  },
  methods: {
    getCate() {
      this.axios("app01/cate/").then((res) => {
        console.log(res.data);
        this.cate_list = res.data.cate_list;
      });
    },
  },
  created() {
    this.getCate();
  },
};
</script>

<style scoped>
</style>

效果

Django 无限级分类

结论

利用django模型提供的自关联构造首页数据,一级分类下面嵌套二级分类,二级分类下面嵌套三级等等,利用`related_name`实现向下查找即可!!!
上一篇:RedisTemplate方法详解


下一篇:C#解析DLL————反射