如何使用 Django 从一个查询中的多个表中进行选择?
我有两张表,一张“公司”和一张“员工”:
class Company(models.Model):
name = models.CharField(max_length=60)
class Employee(models.Model):
name = models.CharField(max_length=60)
company = models.ForeignField(Company)
我想列出表中的每个员工,公司旁边。这很简单,只需调用 employees = Employee.objects.all()
并在模板循环中调用 {{employee.company.name}}
即可。
此解决方案的问题在于,它将为循环中的每个项目创建一个新查询。因此,对于每个员工,都会有一个对公司的查询,如下所示:
SELECT `company`.`id`, `company`.`name`
FROM `company`
WHERE `company`.`id` = 1 # This will of course be the employee.company_id
相反,我希望最初在获取员工的同一查询中进行此连接。像这样的事情:
SELECT `employee`.`name` AS `name`,
`company`.`name` AS `company_name`
FROM `employee` INNER JOIN `company` ON `employee`.`company_id` = `company`.`id`
Is this possible with the Django QuerySet?如果没有,有什么办法可以解决这个问题(没有原始sql)?或者这种行为应该被忽略、缓存并被视为“优化”?
I have two tables, one "Company" and one "Employee":
class Company(models.Model):
name = models.CharField(max_length=60)
class Employee(models.Model):
name = models.CharField(max_length=60)
company = models.ForeignField(Company)
And I want to list every Employee in a table, with the Company next to it. Which is simple enough by calling employees = Employee.objects.all()
and in the template loop trough it and calling {{employee.company.name}}
.
The problem with this solutions is that it will be created a new query for each item in the loop. So for each Employee there will be one query to Company looking something like this:
SELECT `company`.`id`, `company`.`name`
FROM `company`
WHERE `company`.`id` = 1 # This will of course be the employee.company_id
Instead I wish to make this join initially in the same query getting the Employees. Something like this:
SELECT `employee`.`name` AS `name`,
`company`.`name` AS `company_name`
FROM `employee` INNER JOIN `company` ON `employee`.`company_id` = `company`.`id`
Is this possible with the Django QuerySet? If not, is there a way I can work around to solve this(without raw sql)? Or should this behavior be ignored, cached and considered "optimized"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 select_lated() 将预先填充适当的属性:
Using select_related() will pre-populate the appropriate attributes:
这是一个老问题,让我提供一个新答案。
实际上,你可以这样做:
然后,Django 会自动查找 Company 类并为你找到公司名称。
在模板页面,使用 {{employees.company__name}} 即可正确显示公司名称。
It is an old question, let me provide a new answer.
Actually, you can do this:
then, Django will automatically lookup Company class and find the company name for you.
on the template page, use {{employees.company__name}} then it will display the company name correctly.
我想您正在寻找的是查询集的 select_lated 方法。
请参阅文档
I guess what you're looking for is the select_related method of your queryset.
See the doc
使用原始查询
With raw queries