Skip to main content
 首页 » 编程设计

python之多个表在django中的单个查询集中基于外键连接

2024年08月28日25三少

我在我的 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) 

请您参考如下方法:

使用select_related()

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

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