我正在使用django ORM通過查詢使用組獲取數據。 原始PostgreSQL的查詢是 -Django Group按查詢?
select date_trunc('day', time) as Time ,count(status) from table where group_id='2177' and status=1 group by date_trunc('day', time) order by time desc limit 7 offset 0;
和它返回正確的輸出..
time | count
---------------------------+-------
2017-05-04 00:00:00+05:30 | 12
2017-05-03 00:00:00+05:30 | 26
2017-05-02 00:00:00+05:30 | 25
2017-05-01 00:00:00+05:30 | 26
2017-04-30 00:00:00+05:30 | 26
2017-04-29 00:00:00+05:30 | 26
2017-04-28 00:00:00+05:30 | 26
(7行)
我使用Django的註釋功能來達致這 - 這裏是django查詢 -
records = TableModel.objects.filter(
group_id=group_id,
status=1,
time__range = get_time_range(range)
).annotate(
period=DateTrunc('day', 'time') ,
count=Count('status')
).annotate(
period = DateTrunc('day', 'time')
).order_by('-time')
在Debug上,我發現django是我的它nternally轉換爲 -
SELECT "table"."id", "table"."time", "table"."status", "table"."group_id", DATE_TRUNC('day', "table"."time") AS "period", COUNT("table"."status") AS "count" FROM "table" WHERE ("table"."group_id" = '2177' AND "table"."status" = 1 AND "table"."time" BETWEEN '2017-04-28 11:47:21.421755+00:00' AND '2017-05-05 11:47:21.421755+00:00') GROUP BY "table"."id", DATE_TRUNC('day', "table"."time") ORDER BY "table"."time" DESC;
這裏是其O/P(它包含更多的行數) - 它利用(ID,DATE_TRUNC開始組
id | time | status | group_id | period | count
--------+---------------------------+----------------------+------------+---------------------------+-------
267821 | 2017-05-04 10:36:13+05:30 | 1 | 2177 | 2017-05-04 00:00:00+05:30 | 1
267790 | 2017-05-04 09:36:35+05:30 | 1 | 2177 | 2017-05-04 00:00:00+05:30 | 1
267786 | 2017-05-04 09:30:44+05:30 | 1 | 2177 | 2017-05-04 00:00:00+05:30 | 1
267735 | 2017-05-04 08:36:09+05:30 | 1 | 2177 | 2017-05-04 00:00:00+05:30 | 1
267696 | 2017-05-04 07:36:32+05:30 | 1 | 2177 | 2017-05-04 00:00:00+05:30 | 1
267650 | 2017-05-04 06:36:14+05:30 | 1 | 2177 | 2017-05-04 00:00:00+05:30 | 1
267603 | 2017-05-04 05:36:14+05:30 | 1 | 2177 | 2017-05-04 00:00:00+05:30 | 1
....
....
(149 rows)
默認IE( 'day',「table」,「time」))字段雖然我在y Django ORM Query中沒有提到。結果,輸出將會改變。
Django ORM默認情況下會考慮id字段嗎? 有什麼辦法解決它?
你爲什麼要添加兩個註釋? –
我試圖實現也使用單註釋,但徒勞無功。 – tom