我刚刚开始实践Python-django
我正在使用django视图中的查询尝试从DB中过滤对象。从网址传来三个参数,我想做一个'或者'对参数的条件。很少有参数可以为空。
if 'custName' in request.GET :
custName = request.GET['custName']
if custName is not None and custName != '':
files_name=LopFtsMLoanFilesMaster.objects.filter(customer_name__contains=custName)
if 'custId' in request.GET and request.GET['custId']:
custId = request.GET['custId']
if custId is not None and custId != '':
files_id=LopFtsMLoanFilesMaster.objects.filter(customer_id__containis=custId)
if 'address' in request.GET and request.GET['address']:
address= request.GET['address']
if address is not None and address != '':
files_address =LopFtsMLoanFilesMaster.objects.filter(original_address1__contains=address)
files = files_name | files_id | files_address
return render(request, 'file_enquiry.html',
{'results': files})
但我收到local variable 'files_id' referenced before assignment
错误。
答案 0 :(得分:0)
如果'custId' in request.GET and request.GET['custId']
为false,则files_id
永远不会被定义,但您想无条件地引用它。因此,您必须在条件之前定义默认值(例如set()
),以确保始终定义它。
您的代码可以大大简化:
def filtered(request_param, model_field):
param_val = request.GET.get(request_param) # returns None if request_param is not in request.GET
if not param_val: # if param_val in (None, '')
return set()
return LopFtsMLoanFilesMaster.objects.filter(**{model_field + '__contains': param_val})
files = (filtered('custName', 'customer_name') |
filtered('custId', 'customer_id') |
filtered('address', 'original_address'))