Skip to main content
 首页 » 编程设计

python之将 GET 请求参数转换为 int ... 如果它是数字

2025年05月04日15开发

假设我正在向用户显示一些数据,我希望用户能够使用 GET 表单对数据库中的数字字段执行某种过滤,所以我有这样的东西

code = request.GET.get('code') 
condition = {}  
if( code is not None and int(code) > 0 ): 
  condition['code'] = int(code) 
 
Somemodel.objects.filter(**condition) 

但这只有在我的代码包含数字时才有效,否则我会收到此错误

invalid literal for int() with base 10: '' 

那么处理这个问题的 pythonic 方法是什么?我应该使用 try/except block 吗?考虑到我可能会添加其他过滤器,我更喜欢在同一个 if 语句中处理这个问题

请您参考如下方法:

isnumeric 可以检查 code 是否可以cast 为 int 并检查 code 为正数(当转换为整数时)因此替换 int(code) > 0:

if code is not None and code.isnumeric(): 
    condition['code'] = int(code)