我尝试在 pgadmin 中运行以下 SQL 查询,它成功了:
SELECT <columns>
FROM <tables>
WHERE
date_visited >= '2023-05-26 07:05:00'::timestamp
AND date_visited <= '2023-05-26 07:07:00'::timestamp
AND url LIKE '%/mymodule/api/myurl/%';
我想在 django Rest 端点中调用相同的 url。所以,我编写了如下代码:
with connection.cursor() as cursor:
cursor.execute('''
SELECT <columns>
FROM <tables>
WHERE
date_visited >= '%s'::timestamp
AND date_visited <= '%s'::timestamp
AND url LIKE '%%%s%%';
''', [from_date, to_date, url])
但它给了我列表索引超出范围错误。我想我弄错了 '%%%s%%'
。我尝试使用 %%
在原始查询中扩展 %
。但这似乎不起作用。这里出了什么问题?
最佳答案
MyModel.objects.filter(
date_visited__between=('2023-05-26 07:05:00', '2023-05-26 07:07:00'),
<b>url__contains='/mymodule/api/myurl/'</b>,
)
这里我们可以使用__contains
lookup [Django-doc] 区分大小写匹配。
关于python - 在 django sql 查询中转义 % 会导致列表超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76352024/