如何合并并从多个表中获取单个 id 的数据
How to combine and get data from multiple tables for a single id
table答:
................
id name age |
................
1 G 29 |
2 A 30 |
................
table B : (table b 在 tableA_id 字段中有 table A 的多个外键)
id phone rank tableA_id
1 98989 A 1
2 98989 C 1
3 98989 D 2
table C : (table C 在 tableA_id 字段中有 table A 的外键,来了多个)
id notes email tableA_id
1 98989 A@gmail.com 1
2 98989 C@gmail.com 1
在我的例子中,我想从所有 table 中获取所有数据,并希望在单个页面中显示。我想要的是我想要一个查询来获取所有的所有数据
三个 table 和一个查询集。
我发送的 id 是 Table_id = 1
那么我怎样才能从所有 table 中获取 table 1 的数据 任何人都可以告诉我,现在我是新来的
好吧,您可能无法在单个查询中完成。但是使用 prefetch_related
你可以加载所有相关的表,这样 DB 的命中率就会降低。例如:
# 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())
table答:
................
id name age |
................
1 G 29 |
2 A 30 |
................
table B : (table b 在 tableA_id 字段中有 table A 的多个外键)
id phone rank tableA_id
1 98989 A 1
2 98989 C 1
3 98989 D 2
table C : (table C 在 tableA_id 字段中有 table A 的外键,来了多个)
id notes email tableA_id
1 98989 A@gmail.com 1
2 98989 C@gmail.com 1
在我的例子中,我想从所有 table 中获取所有数据,并希望在单个页面中显示。我想要的是我想要一个查询来获取所有的所有数据 三个 table 和一个查询集。 我发送的 id 是 Table_id = 1 那么我怎样才能从所有 table 中获取 table 1 的数据 任何人都可以告诉我,现在我是新来的
好吧,您可能无法在单个查询中完成。但是使用 prefetch_related
你可以加载所有相关的表,这样 DB 的命中率就会降低。例如:
# 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())