dotnet developer dotnet developer - 5 months ago 14
Python Question

Python - django: Reading multiple request params for making queries

I have just started hands-on on Python-django

I am trying filter objects from DB using queries in django view. Three params are passed from the url and I want to do a 'or' condition on the params. Few params can be null.

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})


But I receive
local variable 'files_id' referenced before assignment
error.

Answer

If 'custId' in request.GET and request.GET['custId'] is false then files_id never gets defined, yet you want to refer to it unconditionally. So you must define a default value (e.g. set()) before the condition to ensure that it is always defined.

Your code can be hugely simplified though:

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'))
Comments