1、模型创建
models.py 自关联,获取下级的名称为next
from django.db import models
class Area(models.Model):
"""
区域表
"""
name = models.CharField(max_length=100, verbose_name='名称')
parent = models.ForeignKey('self',on_delete=models.SET_NULL,related_name='son', null=True, verbose_name='父级')
class Meta:
db_table = 'tb_areas'
def __str__(self):
return self.name
2、插入数据
利用MySQL工具 以MySQL Workbench 8.0 CE 为例插入数据
3、序列化器
serializer.py
class AreaSerializer(serializers.ModelSerializer):
"""
地址序列化器
"""
class Meta:
model = Area
fields = '__all__'
4、功能实现
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Area
from .serializer import AreaSerializer
class ObtailAreaView(APIView):
def get(self, request):
parent_id = request.GET.get('parent_id')
if parent_id:
area = Area.objects.filter(pk=parent_id).first()
areas = area.son
else:
areas = Area.objects.filter(parent__isnull=True).all()
area_ser = AreaSerializer(areas, many=True)
return Response({'code': 200, 'areaList': area_ser.data})
5、配置路由
urls.py 做了路由分发
"""
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('area/', views.ObtailAreaView.as_view())
]
6、Vue页面功能(简单实现功能)
<template>
<div>
<h3>省市区三级联动演示</h3>
<div class="form_group">
<label>所在地区:</label>
<select v-model='form.province' @change='getCity(form.province)'>
<option :value="i.id" v-for='i in province_list'>{{ i.name }}</option>
</select>
<select v-model='form.city' @change='getArea(form.city)'>
<option :value="i.id" v-for='i in city_list'>{{ i.name }}</option>
</select>
<select v-model='form.area'>
<option :value="i.id" v-for='i in area_list'>{{ i.name }}</option>
</select>
</div>
</div>
</template>
<script>
export default {
data() {
return {
form: {
province: 110000,
},
province_list: [],
city_list: [],
area_list: []
}
},
methods: {
getProvice() {
this.axios.get('address/area/').then(res => {
console.log(res.data)
this.province_list = res.data.areaList
})
},
getCity(provice) {
this.axios.get('address/area/?parent_id=' + provice).then(res => {
this.city_list = res.data.areaList
})
},
getArea(city) {
this.axios.get('address/area/?parent_id=' + city).then(res => {
this.area_list = res.data.areaList
})
},
},
mounted() {
this.getProvice()
}
}
</script>
<style scoped>
select {
width: 125px;
}
</style>
7、效果演示
8、总结
使用自关联,当省份改变的时候获取省份下面的区或市,当市改变的话获取市级下面的县、镇。
|