gpt4 book ai didi

python - 如何在Django中内连接4个表?

转载 作者:太空宇宙 更新时间:2023-11-03 19:48:18 25 4
gpt4 key购买 nike

我们想要一次检索所有表记录,如何在django orm中实现类似SQL查询。

SQL 查询示例:

select * 
from Company_info
inner join Bank_info on Bank_info.manufacturer = Company_info.manufacturer
inner join Company_info on Company_info.manufacturer = Company_info.manufacturer
inner join Transport_info on Transport_info.manufacturer = Company_info.manufacturer

代码:

class Manufacturer(models.Model):
name = models.CharField(max_length=42)

class Bank_info(models.Model):
account = models.CharField(max_length=42)
manufacturer = models.ForeignKey(Manufacturer, on_delete= models.CASCADE)

class Company_info(models.Model):
name= models.CharField(max_length=42)
manufacturer = models.ForeignKey(Manufacturer, on_delete= models.CASCADE)

class Transport_info(models.Model):
name= models.CharField(max_length=42)
manufacturer = models.ForeignKey(Manufacturer, on_delete= models.CASCADE)

最佳答案

您可以使用prefetch_related为此,正如评论中提到的:

Manufacturer.objects.all().prefetch_related('related_name2', 'related_name3', 'related_name4')

事实上,这不会执行 SQL INNER JOIN,而是会在 Python 级别连接预取的对象 - 这将减少使用相关对象字段时对数据库的命中。

关于python - 如何在Django中内连接4个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60003751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com