我有以下观点:
def process(request):
if request.method == 'POST':
data = request.POST
results = Specs.objects.filter(screenGroup = data['screen_user'], storage = data['storage_user'], mSystem = data['system_user'] )
context = {'results' : results}
return render(request, 'process.html', context)
当用户输入三个值时,它会正确过滤,但当它只输入一个或两个(或没有)时,它会过滤传递值None。如果未设置过滤器,有没有办法忽略过滤器?
谢谢!
编辑:
以下代码正在运行,但这显然是一种非常低效的方式:
def process(request):
if request.method == 'POST':
data = request.POST
if(data['screen_user'] != None):
results = Specs.objects.filter(screenGroup = data['screen_user'])
elif (data['storage_user'] != None):
results = Specs.objects.filter(storage = data['storage_user'])
else:
results = Specs.objects.all()
#plus all the other options...
context = {'results' : results}
return render(request, 'process.html', context)
答案 0 :(得分:2)
它被称为validating your form.。有两种方法可以做到这一点:
创建一个django表单并使用myform.is_valid()。您可以阅读in the docs
使用一些'if'语句自己验证(在服务器端或在发送ajax调用之前使用javascript)
答案 1 :(得分:2)
您可以事先构建过滤器:
def process(request):
if request.method == 'POST':
data = request.POST
spec_filter = {}
for attribute in ['screenGroup', 'storage', 'mSystem']:
if attribute in data and data[attribute]:
spec_filter[attribute] = data[attribute]
results = Specs.objects.filter(**spec_filter)
context = {'results' : results}
return render(request, 'process.html', context)
NB :要逐字使用,您必须更改request.POST中传递的变量名称,以匹配Specs
模型中的变量名称。我这样做只是为了说明,但您可以轻松地使用与变量名称相同的原则。在这种情况下,你必须更加冗长。