Converting GET request parameter to int ... if it is numeric
<p>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 <code>GET</code> form so i have something like this </p>

<pre><code>code = request.GET.get('code')
condition = {} 
if( code is not None and int(code) &gt; 0 ):
  condition['code'] = int(code)

Somemodel.objects.filter(**condition)
</code></pre>

<p>but this works only if i code contains a number otherwise i get  this error </p>

<pre><code>invalid literal for int() with base 10: ''
</code></pre>

<p>so what is the pythonic way to handle this problem ? should i use <code>try/except</code> block? i perfer to handle this in the same <code>if</code> statement considering i might add other filters </p>

<p>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 .</p>

<p>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</p>

<p>So the modified code is</p>

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

    Somemodel.objects.filter(**condition)
</code></pre>

<p>Hope it helps :)</p>

python django python-3.x django-1.9