These are my tables:
class Employee(models.Model):
name = models.CharField()
class Job(models.Model):
title = models.CharField()
class Employee_Job(models.Model):
employee_f = models.ForeignKey(Employee, on_delete=models.CASCADE)
job_f = models.ForeignKey(Job, on_delete=models.CASCADE)
class Salary(models.Model):
employee_job_f = models.ForeignKey(Employee_Job, on_delete=models.CASCADE)
@property
def name(self):
return Employee.objects.filter(id = (
Employee_Job.objects.filter(id = self.employee_job_f_id ).first().employee_f
)).first().name
This query seems very long to me, I thought select_related()
should help with this, but it follows foreign keys and return ALL results not the result that is related to THIS instance of Salary.
CodePudding user response:
Yes, you can filter with
@property
def name(self):
Employee.objects.get(
employee_job__salary=self
).name
This will retrieve the employee which has a Employee_Job
that is related to self
as salary.
Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from
toEmployee_Job
EmployeeJob
.