我想使用Django ORM编写类似的内容。
SELECT Count(*) AS total_count,
(SELECT Count(*)
FROM core_subscriber
WHERE ( core_subscriber.os = 'Mac OS X'
AND website_id = 1 )) AS count1,
(SELECT Count(*)
FROM core_subscriber
WHERE ( core_subscriber.device = 'pc'
AND website_id = 1 )) AS count2
FROM core_subscriber
WHERE core_subscriber.website_id = 1;
查询结果应类似于以下内容
total_count | count1 | count2
-------------+--------+--------
3 | 2 | 1
但是我很难使用django ORM编写此查询。
我尝试了以下操作
query_set1 = Subscriber.objects.filter(Q(os='Mac OS X')).filter(website_id=1)
query_set2 = Subscriber.objects.filter(Q(device='pc')).filter(website_id=1)
Subscriber.objects.annotate(count1=Count(query_set1), count2=Count(query_set2)).values('count1', 'count2').filter(website_id=1).count()
和
Subscriber.objects.annotate(count1=Count(Subquery(query_set1)), count2=Count(Subquery(query_set2))).values('count1', 'count2').filter(website_id=1).count()
其他信息
为什么要使用Django ORM?为什么不使用RawSQL?
正在运行时使用Q
对象创建正在创建count1和count2的子查询。
示例:
count1 ~ Subscriber.objects.filter(Q(os='Mac OS X')).filter(website_id=1).count()
count2 ~ Subscriber.objects.filter(Q(device='pc')).filter(website_id=1).count()
,我在解析来自客户端的一些查询后,在运行时创建Q
对象。因此,为了简单起见,我需要能够使用ORM生成查询。