sqlite 如何使用Django在查询中连接3个表

gkl3eglg  于 2022-11-30  发布在  SQLite
关注(0)|答案(1)|浏览(133)

models.py

class Employee(models.Model):
    emp_no = models.IntegerField(primary_key=True)
    first_name = ...
    last_name = ...

    # emp_no first_name  last_name
      ------ ----------  ----------
      10005  Christian   Erde

class DeptEmp(models.Model):
    emp_no = models.ForeignKey(Employee, on_delete=models.CASCADE)
    dept_no = models.ForeignKey(Department, on_delete=models.CASCADE)

    # dept_no_id  emp_no_id 
      ----------  ----------
      d003        10005     

class Department(models.Model):
    dept_no = models.CharField(primary_key=True, max_length=4)
    dept_name = models.CharField(unique=True, max_length=40)

    #  dept_no     dept_name      
       ----------  ---------------
       d003        Human Resources

views.py

class EmpList(ListView):
    queryset = Employee.objects.all().select_related('deptemp').select_related('department')

employee_list.html

{% for emp in object_list %}
    {{ emp.first_name }}
    {{ emp.last_name }}
    {{ emp.department.dept_name }}
{% endfor %}

我在浏览器上收到此错误消息:select_related中给定的字段名称无效:'deptemp'、' department'。选项包括:(无)

zbq4xfa0

zbq4xfa01#

select_related()返回将遵循 * 外键 * 关系的 QuerySet

from django.db import models
class City(models.Model):
    # ...
    pass
class Person(models.Model):
    # ...
    hometown = models.ForeignKey(
        City,
        on_delete=models.SET_NULL,
        blank=True,
    null=True,
    )

class Book(models.Model):
    # ...
    author = models.ForeignKey(Person, on_delete=models.CASCADE)

然后打电话给**Book.objects.select_related('author__hometown')**
例如:

class EmpList(ListView):
    queryset = DeptEmp.objects.all().select_related('emp_no').select_related('dept_no')

雇员列表.html

{% for deptemp in object_list %}
        {{ deptemp.emp_no.first_name }}
        {{ deptemp.emp_no.last_name }}
        {{ deptemp.dept_no.dept_name }}
    {% endfor %}

相关问题