Django实现一对多表模型的跨表查询方法
作者:盖世英雄Zz 时间:2022-04-09 01:53:33
当有两个表,例如一个学生表,一个班级表,是多对一的关系。
方法1:
c = models.Class.object.get(pk=1)
#查询到ID为1的班级
stus = models.Student.object.filter(cls=c)
# 查询出来所有班级为c的学生
#stus是多个对象
#可以循环出结果
for stu in stus :
print stu.id,stu.name
方法2
stus = models.Student.object.filter(cls__name='1703')
#双下划线为跨表查询,查询学生对应的所有cls为1703的学生
方法3
c=models.Class.object.get(pk=1)
#获取ID为1的班级
stus=c.Student_set.all
#获取所有该班级下的所有学生
html页面获取方法
<td>{{ line.student_set.count }}</td>
来源:https://blog.csdn.net/javali1995/article/details/77972898
标签:Django,一对多,跨表,查询
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python 动态导入对象,importlib.import_module()的使用方法
2023-01-24 01:48:47
建立用户体验过程的实用指南
2007-11-19 12:53:00
层叠加的五条叠加法则
2009-05-01 12:07:00
![](https://img.aspxhome.com/file/UploadPic/20095/1/01-99s.gif)
利用Python中xlwt模块操作excel的示例详解
2023-08-16 18:51:47
详解如何利用Python制作24点小游戏
2022-02-04 17:22:42
![](https://img.aspxhome.com/file/2023/2/66882_0s.jpg)
python selenium自动化测试框架搭建的方法步骤
2023-05-24 21:38:49
![](https://img.aspxhome.com/file/2023/9/75899_0s.jpg)
Python实现简单扫雷游戏
2022-03-27 15:05:23
![](https://img.aspxhome.com/file/2023/9/84979_0s.jpg)
MAC中PyCharm设置python3解释器
2021-04-18 08:36:17
![](https://img.aspxhome.com/file/2023/2/123842_0s.png)
Python浅析多态与鸭子类型使用实例
2023-10-25 00:09:06
python程序快速缩进多行代码方法总结
2022-12-06 03:30:38
![](https://img.aspxhome.com/file/2023/3/70243_0s.png)
asp如何最准确地统计在线用户数?
2010-07-11 21:12:00
Python灰度变换中灰度切割分析实现
2021-10-05 12:07:49
![](https://img.aspxhome.com/file/2023/0/97320_0s.png)
Python实现Const详解
2021-06-24 16:18:40
python判断设备是否联网的方法
2022-05-03 12:34:55
Python中如何添加自定义模块
2023-06-09 23:24:38
pip安装Python库时遇到的问题及解决方法
2023-06-20 14:00:01
![](https://img.aspxhome.com/file/2023/1/100961_0s.png)
使用pycharm将自己项目代码上传github(小白教程)
2022-05-02 20:37:06
![](https://img.aspxhome.com/file/2023/6/82526_0s.jpg)
python在地图上画比例的实例详解
2023-06-22 20:54:00
![](https://img.aspxhome.com/file/2023/1/99011_0s.png)
Python学习之yaml文件的读取详解
2023-04-20 14:06:42
![](https://img.aspxhome.com/file/2023/1/109591_0s.jpg)
php中mysql连接方式PDO使用详解
2023-11-06 02:46:43