【发布时间】:2017-04-10 01:51:03
【问题描述】:
我正在尝试在 Django 中创建以下查询
SELECT content_reference , COUNT(reference)
AS total
FROM usage_statistics
WHERE content_type = 'blog'
AND access_date > NOW() - INTERVAL '90' DAY
GROUP BY content_reference
ORDER BY total DESC
LIMIT 10
到目前为止,我想出的是:
result = UsageStatistics.objects.values('content_reference')\
.annotate(total=Count('reference'))\
.order_by('total')
这使得查询
SELECT "usage_statistics"."content_reference", COUNT("usage_statistics"."reference") AS "total"
FROM "usage_statistics"
GROUP BY "usage_statistics"."content_reference"
ORDER BY "total" ASC
LIMIT 21
我不确定如何正确包含:
- AND access_date > NOW() - INTERVAL '90' DAY
- 按总 DESC 排序
以下是我的usage_statistics表结构
CREATE TABLE usage_statistics
(
reference bigint
access_date timestamp with time zone,
ip_address inet NOT NULL,
language_iso text NOT NULL,
content_type character varying(12) NOT NULL,
content_reference text NOT NULL,
passport_user_id bigint
)
【问题讨论】:
标签: python sql django postgresql