【问题标题】:multiple tables join on basis of foreign key in single query set in django?多个表在 django 中的单个查询集中基于外键连接?
【发布时间】:2013-11-28 10:44:45
【问题描述】:

我在我的 python django 应用程序中使用 sqlite3 数据库:我正在定义我的表结构,它类似于我的实际表架构。

table1 having three column:
1. id | primary key | int
2. name | text
3. address | text

table2 having four column:
1. id | primary key | int
2. name_id | foreign key | int 
3. name_info | text
4. address_info | text


table3 having four column:
1. id | primary key | int
2. name_id | foreign key | int 
3. edu_info | text
4. busin_info | text


table4 having four column:
1. id | primary key | int
2. name_id | foreign key | int 
3. progress_info | text
4. inventory_info | text

等等..

我想根据 forgein 键在 django 的单个查询中访问所有表数据。没有必要所有表都具有相同的记录。

我已经在所有模型中设置了外键。喜欢:

class table(models.Model):
    name = models.ForeignKey(modelname)

【问题讨论】:

  • 问题是什么?
  • 如何在 django 中使用上述条件编写查询

标签: python django django-models django-queryset


【解决方案1】:

使用select_related()

YourModel.objects.select_related().filter(foreign_record__foreign_attribute__gt=foo)

select_related 被转换为 INNER JOIN 查询并立即加载所有数据。

【讨论】:

  • 如果我想根据外键从table2和table3中获取数据,同时table2和table3之间没有直接关系。那我该怎么办?
  • “T2 和 T2 之间没有关系”是什么意思?这没有意义……
  • 不是 T2 和 T2。 table2 和 table3 之间没有关系。
  • 我认为您应该查看数据库布局。据我所知,有两种可能的结果。 1) T1 中的记录以某种方式连接了 T2 和 T3 的内容,因此 T1 外键在 T2 和 T3 中始终是唯一的。在这种情况下,只需将 T2 和 T3 与 1 对 1 关系联系在一起。 2) 如果 T2 或 T3 中有更多相似的外键,你是如何将这些对象链接在一起的?你想要哪一种组合?也许我遗漏了一些东西,但这听起来不像是您的数据库的工作。这不是数据库逻辑,而是应用程序逻辑。
  • 一对多关系。假设 T1 有两条主键 id 为 1|2 的记录。 table2 和 table3 有 12 条记录(8 条记录与密钥 id 1 关联,4 条记录与密钥 id 2 关联)。和同一张桌子3。现在我想从两个表(table2 和 table3)中获取所有记录,这些记录在两个表中都可用。如果我编写简单的核心查询,这很容易,但是我如何在 django 中做你能建议我吗?
猜你喜欢
  • 1970-01-01
  • 2018-03-17
  • 2022-08-20
  • 2015-07-30
  • 2018-08-20
  • 1970-01-01
  • 2016-07-14
  • 2016-08-20
  • 2023-03-12
相关资源
最近更新 更多