這是我做的:
clone = kwargs.get('clone')
if clone:
pre_query = str(clone.query)
pre_query = pre_query.replace('`','"')
else:
qs = clone.get_query_set()
pre_query = str(qs.query)
pre_query = pre_query.replace('`','"')
sql = "\
with etext as ({pre_query}),\
words as (\
select lower(regexp_split_to_table(element_text , E'\\\\W+')) as word \
from etext \
), \
word_lex as (select word, count(*) as cnt,\
to_tsvector('english', COALESCE(word,'')) as t \
from words \
group by 1 order by %s desc) \
select * from word_lex WHERE \
t != '' ".format(pre_query=pre_query)
limit = kwargs.get('limit')
order_by = kwargs.get('order_by')
if limit != None:
sql += 'limit {limit}'.format(limit=limit)
if order_by != None:
sql = sql %(order_by)
else:
sql = sql %('cnt')
return custom_sql(sql)
基本上,我只是使用Django的產生與子查詢創建另一個整個SQL。從那裏,我在隨後的查詢中使用它。
不鏈式過濾器的工作?你的例子可以完美地轉換爲:Table.objects.all()。filter(column__isnull = False) – 2012-07-27 21:17:11
@GonzaloDelgado是的,如果我正在做一個簡單的查詢。在這種情況下,我使用tz_vector創建子表(使用postgres FTS),並使用with as(select blah)是最簡單的構造。 – 2012-07-27 22:07:30
在這種情況下,是的,raw是要走的路https://docs.djangoproject.com/en/dev/topics/db/sql/ – 2012-07-27 22:58:03