如何使用 Django 从一个查询中的多个表中进行选择?

发布于 2024-08-25 06:56:13 字数 928 浏览 10 评论 0原文

我有两张表,一张“公司”和一张“员工”:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

青春如此纠结 2024-09-01 06:56:13

使用 select_lated() 将预先填充适当的属性:

Employee.objects.select_related()

Using select_related() will pre-populate the appropriate attributes:

Employee.objects.select_related()
爱给你人给你 2024-09-01 06:56:13

这是一个老问题,让我提供一个新答案。

实际上,你可以这样做:

employees = Employee.objects.all().values('id','name','company__name')

然后,Django 会自动查找 Company 类并为你找到公司名称。

在模板页面,使用 {{employees.company__name}} 即可正确显示公司名称。

It is an old question, let me provide a new answer.

Actually, you can do this:

employees = Employee.objects.all().values('id','name','company__name')

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.

各空 2024-09-01 06:56:13

我想您正在寻找的是查询集的 select_lated 方法。
请参阅文档

选择相关()

返回一个查询集
自动“跟随”外键
关系,选择
额外的相关对象数据
执行其查询。这是一个
性能助推器,导致
(有时)更大的查询,但是
意味着稍后使用外键
关系不需要数据库
查询

I guess what you're looking for is the select_related method of your queryset.
See the doc

select_related()

Returns a QuerySet that will
automatically "follow" foreign-key
relationships, selecting that
additional related-object data when it
executes its query. This is a
performance booster which results in
(sometimes much) larger queries but
means later use of foreign-key
relationships won't require database
queries

泛滥成性 2024-09-01 06:56:13

使用原始查询

    qry1 = "SELECT c.car_name, p.p_amount FROM pay p, cars c where p.user_id=%s;"

    cars = Cars.objects.raw(qry1, [user_id])

With raw queries

    qry1 = "SELECT c.car_name, p.p_amount FROM pay p, cars c where p.user_id=%s;"

    cars = Cars.objects.raw(qry1, [user_id])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文