Django框架自关联表要如何玩?

2022-10-0309:26:47后端程序开发Comments618 views字数 1044阅读模式

自关联是一种特殊的一对多的关系。
案例:显示广州市的上级地区和下级地区。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28174.html

地区表:id, atitle, aParent_id; # (areas.sql 为批量插入语句)文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28174.html

mysql终端中批量执行sql语句:source areas.sql;文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28174.html

创建好模型类:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28174.html

# 自关联的 ForeignKey 第一个参数为self文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28174.html

class AreaInfo(models.Model):
"""地区模型类"""
# 地区名称
atitle = models.CharField(max_length=20)
# 关联属性,代表当前地区的父级地区
aParent = models.ForeignKey('self', null=True, blank=True,on_delete=models.CASCADE)
然后通过shell生成表 ,然后进入表中查看表的结构:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28174.html

有 aParent_id 的外键 # 自关联文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28174.html

建立视图函数,并且添加到路由中文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28174.html

def areas(request):
"""获取广州市的上级地区和下级地区"""
# 1.获取广州市的信息
area = AreaInfo.objects.get(atitle='广州市')
# 2.查询广州市的信息
parent = area.aParent
# 3.查询广州市的下级地址
children = area.areainfo_set.all() # 一对多查询
# 使用模板
return render(request, 'booktest/areas.html',
{'area': area,
'parent': parent, 'children': children})
然后在模板中使用文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28174.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自关联案例</title>
</head>
<body>
<h1>当前地区</h1>
{{ area.atitle }}<br/>
<h2>父级地区</h2>
{{ parent.atitle }}<br/>
<h3>下级地区</h3>
<ul>
{% for child in children %}
<li>{{ child.atitle }}</li>
{% endfor %}
</ul>
</body>
</html>
运行程序展示出来文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28174.html

版权声明:本文为CSDN博主「还是那个同伟伟」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wei18791957243/article/details/94436852文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28174.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/28174.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定