Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to subquery in queryset in django?

Tags:

python

django

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...

like image 711
gadss Avatar asked Dec 19 '11 01:12

gadss


People also ask

Does Django ORM support subquery?

Django allows using SQL subqueries.

What is F in Django QuerySet?

In the Django QuerySet API, F() expressions are used to refer to model field values directly in the database.

What is Q expression in Django?

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.

How do I join models in 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.


2 Answers

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/

like image 164
Ramast Avatar answered Oct 13 '22 03:10

Ramast


ids = Employee.objects.filter(company='Private').values_list('id', flat=True) Person.objects.filter(id__in=ids).values('name', 'age') 
like image 32
Jan Pöschko Avatar answered Oct 13 '22 02:10

Jan Pöschko