7

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

hretic
  • 999
  • 9
  • 36
  • 78

5 Answers5

13

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)
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
2

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

This function convert GET params to python numeric/bool accordingly:

def convert_params_to_int_or_bool(params):
    for k, v in params.items():
        if v.isnumeric():
            params[k] = int(v)
        if v == 'false':
            params[k] = False
        if v == 'true':
            params[k] = True
Baruch Gans
  • 1,415
  • 1
  • 10
  • 21
0

You can use more pythonic way using try/except block:

try:
    condition["code"] = int(code)
except ValueError:
    pass
Rufat
  • 536
  • 1
  • 8
  • 25
-4

The reason you are getting this error because int() expects the value in number it can be in the form string but it should be a number like "22","33" etc are valid .

But in your case you are passing empty that's why its raising an error. You can achieve your desired output using type(), it helps you in checking the type of number

So the modified code is

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

    Somemodel.objects.filter(**condition)

Hope it helps :)

Sunil Lulla
  • 797
  • 10
  • 18
  • 2
    Except `type(code)` will never be a type `int` at that stage... it'll always be a string that can be empty or otherwise may or may not be a valid int... – Jon Clements Sep 04 '16 at 14:07
  • You can apply other checks after the above check like validating a numeric field etc and could you please elaborate your conditions? – Sunil Lulla Sep 04 '16 at 14:11