How to get multiple field values, when a foreign key is called in django

Question:

I have a Attendance model

class Attendance(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    date = models.DateField()
    day = models.CharField(max_length=10)
    in_time = models.CharField(max_length=5)
    out_time = models.CharField(max_length=5)

Here is the Employee model

class Employee(models.Model):
    emp_id = models.CharField(max_length=10,primary_key=True)
    emp_type = models.CharField(max_length=50)
    name = models.CharField(max_length=100)
    epf_no = models.CharField(max_length=10)
    nic_no = models.CharField(max_length=15)
    appoinment_date = models.DateField()
    termination_date = models.DateField()
    address = models.CharField(max_length=50)
    mobile_no = models.CharField(max_length=15)
    email = models.EmailField(max_length=50)
    bank_name = models.CharField(max_length=50)
    bank_branch = models.CharField(max_length=20)
    bank_acc_name = models.CharField(max_length=20)
    bank_acc_no = models.CharField(max_length=15)
    active_status = models.BooleanField(default=True)

I’m getting data from Attendance model

attendance_record = Attendance.objects.filter(date = date).values()

Here for the employee attribute I’m automatically getting the emp_id field.But I want to get the name field as well
How to do it.?

Answers:

You can access the name through the employee relation:

attendance_record.employee.name

If you want the name in the attendance_record queryset, you can use F('') expressions.

from django.db.models import Avg, Case, Count, F
Attendance.objects.filter(date=date).annotate(name=F('employee__name')).values()
Answered By: Jarad
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.