[英]Django - Get all Columns from Both tables
models.py模型.py
from django.db import models
class DepartmentModel(models.Model):
DeptID = models.AutoField(primary_key=True)
DeptName = models.CharField(max_length=100)
def __str__(self):
return self.DeptName
class Meta:
verbose_name = 'Department Table'
class EmployeeModel(models.Model):
Level_Types = (
('A', 'a'),
('B', 'b'),
('C', 'c'),
)
EmpID = models.AutoField(primary_key=True)
EmpName = models.CharField(max_length=100)
Email = models.CharField(max_length=100,null=True)
EmpLevel = models.CharField(max_length=20, default="A", choices=Level_Types)
EmpPosition = models.ForeignKey(DepartmentModel, null=True, on_delete=models.SET_NULL)
class Meta:
verbose_name = 'EmployeeTable' # Easy readable tablename - verbose_name
def __str__(self):
return self.EmpName
This is my models.py file这是我的 models.py 文件
I have 2 tables and want to join both of them.我有 2 个表,想加入它们。 also want all columns from both tables.
还需要两个表中的所有列。
emp_obj = EmployeeModel.objects.select_related('EmpPosition'). \
only('EmpID', 'EmpName', 'Email','EmpLevel', 'DeptName')
I have tried to do this but there is an error saying EmployeeModel has no field named 'DeptName'
我曾尝试这样做,但出现错误,
EmployeeModel has no field named 'DeptName'
How can I get all these columns?我怎样才能得到所有这些列?
If you want all columns from both tables you don't need the only
clause at all.如果您想要两个表中的所有列,则根本不需要
only
子句。 This is enough:这就够了:
emp_obj = EmployeeModel.objects.select_related('EmpPosition')
If you do need to refer to the DeptName
field of the employee you can follow the foreign key relationship by using a double underscore: EmpPosition__DeptName
如果您确实需要引用员工的
DeptName
字段,您可以使用双下划线遵循外键关系: EmpPosition__DeptName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.