Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
Is there any way to make this filter query smaller

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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 Employee_Job to EmployeeJob.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!