how to subquery in queryset in django?


Question

how can i have a subquery in django's queryset? for example if i have:

select name, age from person, employee where person.id = employee.id and
employee.id in (select id from employee where employee.company = 'Private')

this is what i have done yet.

Person.objects.value('name', 'age')
Employee.objects.filter(company='Private')

but it not working because it returns two output...

1
27
6/8/2016 8:35:01 PM

Accepted Answer

ids = Employee.objects.filter(company='Private').values_list('id', flat=True)
Person.objects.filter(id__in=ids).values('name', 'age')
19
12/19/2011 1:55:06 AM

as mentioned by ypercube your use case doesn't require subquery.

but anyway since many people land into this page to learn how to do sub-query here is how its done.

employee_query = Employee.objects.filter(company='Private').only('id').all()
Person.objects.value('name', 'age').filter(id__in=employee_query)

Source: http://mattrobenolt.com/the-django-orm-and-subqueries/


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon