Skip to main content
 首页 » 编程设计

python之Django 中的内部连接

2025年01月19日32mfrbuaa

我有两张 table

front_employee(Django 中的员工模型)

+-----------------+--------------+------+-----+---------+----------------+ 
| Field           | Type         | Null | Key | Default | Extra          | 
+-----------------+--------------+------+-----+---------+----------------+ 
| id              | int(11)      | NO   | PRI | NULL    | auto_increment | 
| order           | int(11)      | NO   |     | NULL    |                | 
| name            | varchar(100) | YES  |     | NULL    |                | 
| position        | varchar(100) | YES  |     | NULL    |                | 
| description     | longtext     | YES  |     | NULL    |                | 
| employee_img_id | int(11)      | NO   | MUL | NULL    |                | 
| language_id     | int(11)      | NO   | MUL | NULL    |                | 
+-----------------+--------------+------+-----+---------+----------------+ 

还有front_employeepicture(Django中的EmployeePicture)

+-------+--------------+------+-----+---------+----------------+ 
| Field | Type         | Null | Key | Default | Extra          | 
+-------+--------------+------+-----+---------+----------------+ 
| id    | int(11)      | NO   | PRI | NULL    | auto_increment | 
| order | int(11)      | NO   |     | NULL    |                | 
| img   | varchar(100) | YES  |     | NULL    |                | 
+-------+--------------+------+-----+---------+----------------+ 

我想执行这个查询:

SELECT a.id, a.name, b.img 
FROM front_employee a 
INNER JOIN front_employeepicture b 
ON a.employee_img_id = b.id 

现在我有

context['employee'] = Employee.objects.all().order_by('order') 

我试过类似的方法

context['employee'] = Employee.objects.select_related('EmployeePicture') 

没有结果。有什么想法吗?

请您参考如下方法:

Django的ORM真的很强大。实际上,您永远不必那样做连接。当您访问该字段时,ORM 会即时执行连接,返回您想要的结果。

first_employee = Employee.objects.all().first() 
employee_picture = first_employee.employee_img 

然后 employee_picture 应该有第一个员工的照片。它需要在内部做一个内部连接来解决这个问题,但 Django 为你隐藏了所有这些。 (我可能把你的变量名弄错了,抱歉)。

select_related 所做的是为查询集中的每个对象预取一个关系。这意味着更少的来回访问数据库,从而使您的功能更快。但是,Django 允许您仅通过访问属性来遍历关系。

尝试在你的 django shell 中弄乱这些东西。我会将 django_extensions 添加到您的应用程序(pip install django-extensions,然后将 django_extensions 添加到您的 INSTALLED_APPS,然后运行 ​​python manage.py shell_plus) .如果没有,python manage.py shell 工作正常,但您必须手动导入模型。