python - How to build Django queries to get list of data that satisfy many conditions?
问题描述
I am trying to get a list of user_id by executing such sqlite query.
SELECT
u.user_id
FROM
users u
WHERE
u.role_id IN ( 1, 2 )
AND ( SELECT COUNT( * ) FROM purchases p WHERE p.user_id = u.id ) >= 1
AND (
SELECT
tagged.tag_id
FROM
tagged
INNER JOIN ( SELECT polled.answer_id FROM polled WHERE polled.user_id = u.id ) AS a
WHERE
a.answer_id = tagged.answer_id
) IN ( 1,2 )
How can run that sql using django orm? It's so hard to understand logic querysets like this...
Users.objects.annotate(cnt=Count('purchases')).filter(Exists(Polled.objects.filter(user=OuterRef('pk')))).filter(cnt__gt=1).filter(role__in=[1, 2]).values_list('user_id', flat=True)
Please help to build correct queries to get list of users that satisfy the conditions. Thanks.
解决方案
推荐阅读
- java - 带有 Java REST API 的泛型
- android - Moshi 1.11.0 - 如何将枚举中的值回退为空?
- javascript - Chrome FileReader 为大文件返回空字符串 (>= 300MB)
- javascript - 在 useState Hook 中更新对象属性,属性名称应从变量中获取
- android - 停止对作为正文参数传递的 json 请求进行编码的改造
- python - 在python中分配所有数值
- ms-word - 删除 ms word 页脚中的水平线
- php - Symfony - “framework.test”配置未设置为 true
- c# - 使用 LINQ 和实体框架时如何避免重复 ToList?
- python - 如何在不打开浏览器的情况下抓取执行的 JavaScript?