gpt4 book ai didi

python - 如何使用 Django 连接 3 个表进行查询

转载 作者:行者123 更新时间:2023-11-28 22:28:04 26 4
gpt4 key购买 nike

模型.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

View .py

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

员工列表.html

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

我在浏览器上收到此错误消息:无效的字段名称在 select_related: 'deptemp', 'department' 中给出。选择是:(无)

最佳答案

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')

employee_list.html

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

关于python - 如何使用 Django 连接 3 个表进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43772163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com