2

有谁知道我如何让 Django Filter 构建 OR 语句?我不确定是否必须使用 Q 对象,我认为我需要某种类型的 OR 管道,但这似乎不对:

    filter_mfr_method = request.GET.getlist('filter_mfr_method')
    for m in filter_mfr_method:
        designs = designs.filter(Q(mfr_method = m) | m if m else '')
        # Or should I do it this way?
        #designs = designs.filter(mfr_method = m | m if m else '')

我希望这是:

SELECT * FROM table WHERE mfr_method = 1 OR mfr_method = 2 OR mfr_method = 3

编辑:这是有效的

    filter_mfr_method = request.GET.getlist('filter_mfr_method')
    list = []
    for m in filter_mfr_method:
        list.append(Q(mfr_method = m))

    designs = designs.filter(reduce(operator.or_, list))
4

2 回答 2

1

我以前用过的东西:

qry = None
for val in request.GET.getlist('filter_mfr_method'):
    v = {'mfr_method': val}
    q = Q(**v)
    if qry: 
        qry = qry | q
    else: 
        qry = q

designs = designs.filter(qry)

这取自我的一个查询构建器。

于 2013-04-16T15:47:30.103 回答
1

关于什么:

import operator 

filter_mfr_method = request.GET.getlist('filter_mfr_method')
filter_params = reduce(operator.or_, filter_mfr_method, Q())
designs = designs.filter(filter_params)
于 2013-04-16T15:33:54.430 回答