2

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

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

所以:

with blah as (select * from table)

select * from blah where blah.column is not null
4

1 回答 1

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

于 2012-07-31T19:01:35.620 回答