man utd
man utd

Reputation: 37

Django orm query to multiple tables subquery

I am trying to write a "complex" subquery using django orm.

I have the below tables.

Employer table
employer_id
employer_name


Department Table

department_id

employer_id


Employee Table

employee_name

department_id


My query should return the names of all employees (employee_name) who work for employer with employer_name = "Google".

I have the below sql query and it works just fine:

  select * from Employee_Table where department_id in (
     select department_id from Department_Table where employer_id in (
       select employer_id FROM Employer_Table WHERE employer_name="GOOGLE" ) ) 

I am new to Django orm queries and would appreciate some help in understanding how this works in django orm.

Thank you.

Upvotes: 0

Views: 462

Answers (1)

schillingt
schillingt

Reputation: 13731

What you're looking for is something like this:

employers = Employer.objects.filter(name='GOOGLE')
employees = Employee.objects.filter(department__employer__in=employers)

I believe that'll generate a subquery, but probably not the one you have written.

What Robin suggested would be this:

employees = Employee.objects.filter(department__employer__name='GOOGLE')

Which is likely to be more efficient at the db level.

Upvotes: 2

Related Questions