Converting GET request parameter to int ... if it is numeric
Asked Answered
P

5

8

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

Perfidy answered 4/9, 2016 at 13:59 Comment(2)
https://mcmap.net/q/41236/-how-can-i-check-if-a-string-represents-an-int-without-using-try-except-duplicate/1005215Geof
Any reason you're not using Django's builtin forms/validation to process the request.GET here?Starkey
B
15

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)
Blueness answered 4/9, 2016 at 14:15 Comment(5)
isnumeric() expects a unicode string? As i am getting AttributeError for "22" but working fine for u"22".Copyreader
@SunilLulla With that Python 3.x tag, I would assume this should work for all strings (which are unicode by default). For Python 2, you could use isdigit.Blueness
in python 2.x i prefer type() for checking int and other datatypes, is that the wrong way of checking?Copyreader
@SunilLulla You cant use type to check for int in this case, since code is a string. But generally, you should consider using isinstance which handles inheritance.Blueness
This worked for me, is envolved int()Durra
P
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.

Pizor answered 4/9, 2016 at 14:30 Comment(0)
B
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
Backstairs answered 17/1, 2022 at 8:12 Comment(0)
R
0

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

try:
    condition["code"] = int(code)
except ValueError:
    pass
Rattlehead answered 15/4, 2023 at 3:50 Comment(0)
C
-5

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

Copyreader answered 4/9, 2016 at 14:5 Comment(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...Starkey
You can apply other checks after the above check like validating a numeric field etc and could you please elaborate your conditions?Copyreader

© 2022 - 2024 — McMap. All rights reserved.