Django - Get all Columns from Both tables

models.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

I have 2 tables and want to join both of them. 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'

How can I get all these columns?

If you want all columns from both tables you don't need the only clause at all. 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

Back to Top