使用django的postgres“with”语句

时间:2012-07-27 20:59:43

标签: django postgresql

是否可以在django查询集中使用with语句?像一个额外的参数。我可以使用.raw,但我只是想知道这是否是一种方法(通过覆盖Query类或其他路径)

作为参考,这需要在select语句之前。

所以:

with blah as (select * from table)

select * from blah where blah.column is not null

1 个答案:

答案 0 :(得分:0)

我就这样做了:

    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来创建另一个子查询。从那里开始,我在随后的查询中使用了它。