如何在python中避免使用过多的if - else块

时间:2013-12-23 21:01:58

标签: python django

我编写了一个类,用于检查输入中的4个参数,并在输出中显示结果列表。 只需要此参数中的一个,因此我有7个if - else嵌套块。 我想指定所述条件正常工作。

如果有更聪明的方法来写这个,我就会徘徊:

if cd['subject'] is None:
    if cd['school'] == '':
        if cd['price']:
            files = File.objects.filter(name__contains=cd['name'], price = '0.0')
        else:
            files = File.objects.filter(name__contains=cd['name'])
    else:
        if cd['price']:
            files = File.objects.filter(name__contains=cd['name'], school = cd['school'], price = '0.0')
        else:
            files = File.objects.filter(name__contains=cd['name'], school = cd['school'])
else:
    if cd['school'] == '':
        if cd['price']:
            files = File.objects.filter(name__contains=cd['name'], subject = cd['subject'], price = '0.0')
        else:
            files = File.objects.filter(name__contains=cd['name'], subject = cd['subject'])
    else:
        if cd['price']:
            files = File.objects.filter(name__contains=cd['name'], school = cd['school'], subject = cd['subject'], price = '0.0')
        else:
            files = File.objects.filter(name__contains=cd['name'], school = cd['school'], subject = cd['subject'])
return render(request, 'search.html', {'files': files, 'request': request})

2 个答案:

答案 0 :(得分:6)

在内部,您传递给函数的关键字参数只是dict。因此,自己构建它并使用**name语法将其传递给函数:

args = {}

args['name__contains'] = cd['name']

if cd['subject'] is not None:
    args['subject'] = cd['subject']
if cd['school'] != '':
    args['school'] = cd['school']
if cd['price']:
    args['price'] = cd['price']

files = File.objects.filter(**args)
return render(request, 'search.html', {'files': files, 'request': request})

答案 1 :(得分:0)

使用关键字args构建一个dict,用于调用filter(),然后使用**kwargs语法传递它。