Converting GET request parameter to int ... if it is numeric

hretic picture hretic · Sep 4, 2016 · Viewed 7.8k times · Source

lets say i'm showing some data to user , i want user to be able to perform some sort of filtering on a numeric field in the database using a GET form so i have something like this

code = request.GET.get('code')
condition = {} 
if( code is not None and int(code) > 0 ):
  condition['code'] = int(code)

Somemodel.objects.filter(**condition)

but this works only if i code contains a number otherwise i get this error

invalid literal for int() with base 10: ''

so what is the pythonic way to handle this problem ? should i use try/except block? i perfer to handle this in the same if statement considering i might add other filters

Answer

Moses Koledoye picture Moses Koledoye · Sep 4, 2016

isnumeric could check if code can be cast to int and also check that code is positive (when converted to an integer) thus replacing int(code) > 0:

if code is not None and code.isnumeric():
    condition['code'] = int(code)