我们想要一次检索所有表记录,如何在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 级别连接预取的对象 - 这将减少使用相关对象字段时对数据库的命中。
我是一名优秀的程序员,十分优秀!