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...
Django allows using SQL subqueries.
In the Django QuerySet API, F() expressions are used to refer to model field values directly in the database.
Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects we can make complex queries with less and simple code. For example, this Q object filters whether the question starts wiht 'what': from django.
Join can be done with select_related method: Django defines this function as Returns a QuerySet that will “follow” foreign-key relationships, selecting additional related-object data when it executes its query.
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/
ids = Employee.objects.filter(company='Private').values_list('id', flat=True) Person.objects.filter(id__in=ids).values('name', 'age')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With