我有这个查询,我正在尝试使用Django ORM重新创建。
select
count(tickets.id),
date
from
tickets,
generate_series('2000-01-01', date_trunc('month', CURRENT_DATE), interval '1 month') as date
where
(date >= created AND date < resolved)
group by
date;
我想我很接近这个:
tkts = Ticket.objects.extra(
tables=["generate_series('2000-01-01', date_trunc('month', CURRENT_DATE), interval '1 month') as date"],
where=["(date >= created AND date < resolved)"],
order_by=['date'],
).values('date').annotate(cnt=Count('id'))
但我收到错误:
FieldError:无法将关键字'date'解析为字段。
当我将查询减少到此时:
tkts = Ticket.objects.extra(
tables=["generate_series('2000-01-01', date_trunc('month', CURRENT_DATE), interval '1 month') as date"],
where=["(date >= created AND date < resolved)"])
我可以看到表中的值被转义并用双引号括起来(来自connections[app].queries
:
'SELECT ...
FROM
"tickets",
"generate_series(\'2000-01-01\', date_trunc(\'month\', CURRENT_DATE), interval \'1 month\') as date"
WHERE
("tickets"."queue" IN (1,2,3) AND
((date >= created AND date < resolved)))
ORDER BY "tickets"."created" DESC LIMIT 21'
那么我可以用mark_safe
来避免这种情况吗?我想我可以创建一个存储过程来替换generate_series
的东西,但如果可能的话我宁愿不改变数据库。