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
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)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With