你能用django extra(select = {})来选择多个字段吗?

时间:2015-11-03 11:03:19

标签: django django-models

我想在我的django产品查询集中添加两个新字段,我这样做

products = Product.objects.filter(company=company).filter(Q(name__icontains=search_term) | Q(code__icontains=search_term))
products = products.extra(select={"is_distributed": product_is_distributed_query(False)})
products = products.extra(select={"expense_type": product_expense_type_query(False)})

但是两个查询(product_is_distributed_query和product_expense_type_query)只是返回不同的字段。我只能通过一个查询返回两个字段,只用一个额外的(select {})吗?

查询将如下:

def product_is_distributed_query(use_product_code):
product_query = """
select vt.is_distributed, coalesce(et.name, '')
from (
    SELECT
        cp.id, 
    CASE WHEN SUM(coalesce(snp.id, 0)) > 0 THEN true
        ELSE false
    END as is_distributed,
    max(coalesce(snp.expense_type_id, 0)) as maxId1

    FROM
        core_product AS cp
    LEFT JOIN
        stock_non_product AS snp
    ON (cp.name = snp.name """
product_query = product_query + ("AND cp.code = snp.code" if use_product_code else "")
product_query += """    
        AND cp.company_id = snp.company_id AND snp.is_deleted = false)
    LEFT JOIN expense_type as et ON(snp.expense_type_id = et.id AND snp.company_id = et.company_id)
    WHERE
        cp.id = core_product.id
        AND cp.company_id = core_product.company_id
    --         AND snp.company_id = core_product.company_id
    GROUP BY
        cp.id
) as vt
-- LEFT JOIN stock_non_product AS snp ON(snp.id = maxId)
LEFT JOIN expense_type as et ON(et.id = vt.maxId)
"""

return product_query

而不是两个与此相同的分离查询,但返回一个或另一个字段

0 个答案:

没有答案