如何在django中查询queryset中的子查询? [英] how to subquery in queryset in django?

查看:1562
本文介绍了如何在django中查询queryset中的子查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在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')

这是我已经做了什么

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

但它不工作,因为它返回两个输出...

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

推荐答案

ids = Employee.objects.filter(company='Private').values_list('id', flat=True)
Person.objects.filter(id__in=ids).values('name', 'age')

这篇关于如何在django中查询queryset中的子查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆