Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 247
hretic Avatar asked Mar 12 '23 05:03

hretic


2 Answers

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)
like image 120
Moses Koledoye Avatar answered Mar 19 '23 10:03

Moses Koledoye


You should use a Django form with one or more IntegerFields; they do this conversion for you, then you can get the result from cleaned_data.

like image 35
Daniel Roseman Avatar answered Mar 19 '23 10:03

Daniel Roseman