1.从一到多和从多到一的关联查询
2.通过模型类实现关联查询
3.自关联-一种特殊的一对多
class AreaInfo(models.Model):
atitle=models.CharField(max_length=20)
#关系属性
aparent=models.ForeignKey('self',on_delete=models.CASCADE,null=True,blank=True)
4.执行迁移
5.增加视图函数
def areas(request):
#获取广州市的信息
area = AreaInfo.objects.get(atitle='广州市')
#获取广州市的上级地区
parent = area.aparent
#获取广州市的下级地区
children = area.areainfo_set.all()
return render(request,'booktest/areas.html',{'area':area,'parent':parent,'children':children})
6.增加视图模板
自关联案例
当前地区
{{area.atitle}}
父级地区
{{parent.atitle}}
下级地区
{% for child in children%}
- {{child.atitle}}
{% endfor %}
7.增加路由
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^index$', views.index),
url(r'^create$', views.create),
url(r'^delete(\d+)$', views.delete),
url(r'^areas$', views.areas),
]
8.访问http://127.0.0.1:8000/areas