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'。选项包括:(无)
1条答案
按热度按时间zbq4xfa01#
select_related()
返回将遵循 * 外键 * 关系的 QuerySet。然后打电话给**
Book.objects.select_related('author__hometown')
**例如:
雇员列表.html