how to subquery in queryset in django?

后端 未结 5 1617
予麋鹿
予麋鹿 2020-12-14 00:49

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          


        
5条回答
  •  不知归路
    2020-12-14 01:36

    You can create subqueries in Django by using an unevaluated queryset to filter your main queryset. In your case, it would look something like this:

    employee_query = Employee.objects.filter(company='Private')
    people = Person.objects.filter(employee__in=employee_query)
    

    I'm assuming that you have a reverse relationship from Person to Employee named employee. I found it helpful to look at the SQL query generated by a queryset when I was trying to understand how the filters work.

    print people.query
    

    As others have said, you don't really need a subquery for your example. You could just join to the employee table:

    people2 = Person.objects.filter(employee__company='Private')
    

提交回复
热议问题