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)
full_name = models.CharField()
@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.
Follow up on Willem Van Onsem's answer:
I added a couple more rows to my tables and I'm using this query in the save() function and suddenly I'm getting this error:
get() returned more than one which is a popular error.
I made the query a tad smaller too:
def save(self, *args, **kwargs):
self.full_name = Employee_Job.objects.get(
salary=self
).name + " 's salary"
super(salary, self).save(*args, **kwargs)
I checked to see what SQL query Django is running behind the scenes and I found the culprit:
SELECT [blog_employee_job].[id], [blog_employee_job].[employee_f_id], [blog_employee_job].[job_f_id] FROM [blog_employee_job] LEFT OUTER JOIN [blog_salary]
ON ([blog_employee_job].[id] = [blog_salary].[employee_job_f_id])
WHERE [blog_salary].[id] IS NULL
I think WHERE [blog_salary].[id] IS NULL is the culprit and I don't understand why and I don't know how to fix this, searched a lot and went through Docs a lot as well.
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_JobEmployeeJob.