我有这个查询,我试图用 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:无法将关键字“日期”解析为字段。
当我将查询简化为:
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
东西,但如果可能的话,我宁愿不改变数据库。