0
if 'category' and 'something' and 'from_price' and 'to_price' in request.GET:
        category = request.GET['category']
        something = request.GET['something']
        from_price = request.GET['from_price']
        to_price = request.GET['to_price']

        d = Data.objects.filter(Q(category = category)| Q(something = something)|Q(price__gt=from_price)|Q(price__lt=to_price))

如果我只填写(例如)如何过滤这些数据to_price?(不是所有字段)

我的代码不能正常工作

4

2 回答 2

0
sum(1 for x in ('category', 'something', 'from_price', 'to_price') if x in request)

返回当前字段的数量(0 到 4)然后您可以检查此数字是 2 还是 3。

于 2013-02-21T12:09:39.780 回答
0

关于什么

import operator
conds = (request.GET.get(f) for f in ('category', 'something', 'from_price', 'to_price'))
if any(conds):
    d = Data.objects.filter(
            reduce(operator.or_, 
                (Q(**{a:b}) for a,b in zip(('category', 'something', 'price__gt', 'price__lt'), filter(lambda x: x, conds)))))

请注意, d 仅在if语句和成功执行后的任何代码中可用。

# or

category = request.GET.get('category')
something = request.GET.get('something')
from_price = request.GET.get('from_price')
to_price = request.GET.get('to_price')

q = Q()
if category:
    q |= Q(category=category)
if something:
    q |= Q(something=something)
if from_price:
    q |= Q(price__gt=from_price)
if to_price:
    q |= Q(price__lt=to_price)

d = Data.objects.filter(q)
于 2013-02-21T12:19:00.180 回答