hretic hretic - 3 months ago 8
Python Question

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

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

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

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