首页 > 解决方案 > 如何组合并从多个表中获取单个 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 的数据 任何人都可以知道请让我现在我是新来的

标签: pythondjangodjango-admindjango-queryset

解决方案


好吧,可能你不能在单个查询中做到这一点。但是使用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())

推荐阅读