💎场景实例
很多网站的首页上都会展示很多的分类,诸如:
京东
,淘宝
,C站
等等,都是利用Django模型中的自关联
做的,今天做一期无限级分类的Blog!
💎模型创建
定义了一个基本的模型用于继承(创建时间和更新时间)
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 Cart(BaseModel):
name = models.CharField(max_length=50)
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='son')
level = models.IntegerField(null=True, blank=True)
top_parent = models.IntegerField(null=True, blank=True)
class Meta:
db_table = 'cart'
💎功能实现
根据前端所需要的数据来构造数据
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Cart
from .serializer import CartSerializer
def getCart(carts):
"""
解析分类
"""
dict = {}
list = []
for i in carts:
dict[i['id']] = i
for j in carts:
parent_id = j['parent']
if parent_id:
if 'son' not in dict[parent_id]:
dict[parent_id]['son'] = []
dict[parent_id]['son'].append(j)
else:
list.append(j)
return list
class CartView(APIView):
"""
获取分类
"""
def get(self, request):
# 查询分类
cart_obj = Cart.objects.all()
cart_ser = CartSerializer(cart_obj, many=True)
cart_list = getCart(cart_ser.data)
return Response({'code': 200, 'cartList': cart_list})
💎路由配置
"""
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.urls import path
from . import views
urlpatterns = [
path('home/', views.CartView.as_view()) # 首页分类接口
]
💎前端功能
用
vue-cli
脚手架
<template>
<div>
<h3>无限级分类展示</h3>
<div v-for="i in cart_list">
<p v-for="j in i.son">
<span>{{ i.name }}</span>  
<span>{{ j.name }}</span> 
<span v-for="k in j.son">{{ k.name }}</span> 
</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
cart_list: []
}
},
methods: {
getCart() {
this.axios.get('cart/home/',).then(res => {
this.cart_list = res.data.cartList
})
}
},
mounted() {
this.getCart()
}
}
</script>
💎效果展示
主要是实现后端功能,页面效果可忽略!
💎总结
利用django模型提供的自关联构造首页数据,一级分类下面嵌套二级分类,二级分类下面嵌套三级等等,利用**related_name**
实现向下查找即可!!!