python - 如何组合并从多个表中获取单个 id 的数据
问题描述
表 A:
................
id name age |
................
1 G 29 |
2 A 30 |
................
表 B :(表 b 在 tableA_id 字段中具有表 A 的外键,该字段来自多个)
id phone rank tableA_id
1 98989 A 1
2 98989 C 1
3 98989 D 2
表 C :(表 C 在 tableA_id 字段中具有表 A 的外键,该字段来自多个)
id notes email tableA_id
1 98989 A@gmail.com 1
2 98989 C@gmail.com 1
就我而言,我想从所有表中获取所有数据并希望显示在一个页面中。我想要的是我想要一个查询来使用一个查询集从所有三个表中获取所有数据。我发送的 id 是 Table_id = 1 所以我怎样才能从所有表中获取表 1 的数据 任何人都可以知道请让我现在我是新来的
解决方案
好吧,可能你不能在单个查询中做到这一点。但是使用prefetch_related
您可以加载所有相关表,从而减少数据库命中。例如:
# if the models are defined like this:
class TableA(models.Model):
name = models.CharField(...)
age = models.IntegerField(...)
class TableB(models.Model):
table_a = models.ForeignKey(TableA)
class TableC(models.Model):
table_a = models.ForeignKey(TableA)
# then the query will be like this
table_data = TableA.objects.filter(pk=1).prefetch_related('tableb', 'tablec')
for data in table_data:
print(data.name)
print(data.tableb.all().values())
print(data.tablec.all().values())
推荐阅读
- android - 无法通过 Android Oreo 中的 JobScheduler 启动服务
- python - 在 Python (Pandas) 中创建循环,遍历行名并创建分组多索引
- firebase - Firebase 函数从不同路径接收数据和求和
- sockets - Cloud SQL 套接字如何知道要连接到哪个域?
- javascript - 克隆所选元素
- javascript - 使用 JavaScript 交替向列表项添加类
- arrays - 快速复制具有相同地址的对象
- angular - Angular 6:来自资产的图像不能以内联样式工作
- powershell - 删除批处理文件中的注册表项(错误:访问被拒绝)
- php - 配置 MYSQL 但未应用