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
}
]
})