## 首先非常感谢您的阅读,由于项目需要,需要对地区参数进行配置,以下分享以下地区树状结构在Django中的应用
models.py``
class ChinaArea(models.Model):
"""
中国省市区(县)列表
数据来源于高德地图
"""
uuid = models.CharField(max_length=64, unique=True, null=True)
fatherUuid = models.ForeignKey('self', on_delete=models.CASCADE, to_field='uuid', null=True, default=None)
level = models.CharField(max_length=32,verbose_name="级别")
adcode = models.CharField(max_length=32,verbose_name="区域代码")
name = models.CharField(max_length=64,verbose_name="区域名")
center = models.CharField(max_length=32,verbose_name="中心点")
status = models.CharField(max_length=32, default='normal')
createTime = models.DateTimeField(auto_now_add=True)
updateTime = models.DateTimeField(auto_now=True)
数据存入数据库
def area_create(request):
"""
存储地区信息
:param request:
:return:
"""
url = "https://restapi.amap.com/v3/config/district"
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3)'}
params = {
"key": "高德web的key",
"subdistrict": 3
}
res = requests.get(url, params=params, headers=headers)
res.encoding = "utf-8"
# html为json格式的字符串
data = res.text
# 把json格式字符串转为python数据类型
data = json.loads(data)
if data['info'] == "OK":
try:
info = data["districts"][0]
with transaction.atomic():
uuid1 = get_uuid()
country = ChinaArea(
uuid=uuid1,
level=info['level'],
adcode=info['adcode'],
name=info['name'],
center=info['center'],
)
country.save()
for pro in info['districts']:
uuid2 = get_uuid()
province = ChinaArea(
uuid=uuid2,
fatherUuid=country,
level=pro['level'],
adcode=pro['adcode'],
name=pro['name'],
center=pro['center'],
)
province.save()
for cit in pro['districts']:
uuid3 = get_uuid()
city = ChinaArea(
uuid=uuid3,
fatherUuid=province,
level=cit['level'],
adcode=cit['adcode'],
name=cit['name'],
center=cit['center'],
)
city.save()
for are in cit['districts']:
uuid4 = get_uuid()
area = ChinaArea(
uuid=uuid4,
fatherUuid=city,
level=are['level'],
adcode=are['adcode'],
name=are['name'],
center=are['center'],
)
area.save()
except Exception as e:
logging.error(str(e))
print(str(e))
return http_return(400, '失败')
else:
return http_return(400, '响应失败')
return http_return(200, '成功')
数据查询接口提供
@check_admin_rule
def area_query(request):
"""
区域信息获取
:param request:
:return:
"""
uuid = request.GET.get('uuid', '')
areas = ChinaArea.objects.filter(level="province").all()
if uuid != '':
areas = ChinaArea.objects.filter(fatherUuid__uuid=uuid).all()
areaList = []
for area in areas:
areaList.append({
"uuid": area.uuid,
"name": area.name,
})
return http_return(200, "成功", {"area": areaList})