表的自關(guān)聯(lián), 實(shí)現(xiàn)省市區(qū)的聯(lián)動(dòng)
models:
class AreaInfo(models.Model):
title = models.CharField(max_length=20)
pid = models.ForeignKey('AreaInfo', null=True)
- 主鍵使用的默認(rèn)生成的主鍵id
- title存儲(chǔ)省市縣名稱
- pid_id作為外鍵 進(jìn)行自關(guān)聯(lián)
views
定義兩個(gè)view, 一個(gè)用來(lái)返回模板 , 一個(gè)用來(lái)根據(jù)市區(qū)返回對(duì)應(yīng)的json
- area 用來(lái)返回模板
def area(request):
return render(request, 'booktest/area.html')
- getArea 用來(lái)返回json數(shù)據(jù)
def getArea(request, id): # 接收一個(gè)參數(shù)的id, 指modde中的pid屬性對(duì)應(yīng)的字段,即表中的pid_id
area_pid = int(id) # 將參數(shù)轉(zhuǎn)成int類型
if area_pid == 0: # 為0時(shí)表示為查詢省 , 省的pid_id為null
area_data = AreaInfo.objects.filter(pid__isnull=True).values('id', 'title')
else: # 查詢市或者區(qū)縣
area_data = AreaInfo.objects.filter(pid_id=area_pid).values('id', 'title')
area_list = []
# 雖然area_data看起來(lái)像是列表內(nèi)包含多個(gè)字典類型的,
# 但其實(shí)返回的是django.db.models.query.ValuesListQuerySet類型,
# 所以需要自己轉(zhuǎn)成list類型.
# 否則不能進(jìn)行json序列化.
for area in area_data:
area_list.append({'id': area['id'], 'title': area['title']})
# 然后通過(guò)jsonResponse返回給請(qǐng)求方, 這里是list而不是dict, 所以safe需要傳入False.
return JsonResponse(area_list, content_type='application/json', safe=False)
urls
url(r'^area$', views.area, name='area'),
url(r'^getArea/(\d+)$', views.getArea, name='getArea'),
剩下的就是templates了
- booktest/area.html 其中使用的jquery請(qǐng)求數(shù)據(jù)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/static/booktest/js/jquery-1.12.4.min.js"></script>
<script>
getArea = function (a, b) {
$.get('/getArea/' + a, function (dic) {
$.each(dic, function (index, item) {
b.append('<option value="' + item.id + '">' + item.title + '</option>')
})
})
};
$(function () {
pro = $('#pro'); //省
city = $('#city'); //市
dis = $('#dis'); //縣
// 查詢省信息
getArea(0, pro);
//根據(jù)省的改變查詢市的信息
pro.change(function () {
city.empty().append('<option value="">請(qǐng)選擇市</option>');
dis.empty().append('<option value="">請(qǐng)選擇縣</option>');
getArea(this.value, city)
});
//根據(jù)市的改變查詢縣的信息
city.change(function () {
dis.empty().append('<option value="">請(qǐng)選擇縣</option>');
getArea(this.value, dis)
})
})
</script>
</head>
<body>
<select id="pro">
<option value="">請(qǐng)選擇省</option>
</select>
<select id="city">
<option value="">請(qǐng)選擇市</option>
</select>
<select id="dis">
<option value="">請(qǐng)選擇縣</option>
</select>
</body>
</html>

area.gif