Skip to main content
 首页 » 编程设计

python之在 Django 中,如何使用 iexact 检查项目是否不区分大小写匹配

2025年05月04日24del

我正在尝试在我的 Django 应用程序中使用 iexact。

我的数据库中有项目,例如 test、TEST、tEsT 和 TesT。

我正在尝试找出是否有任何形式的 test 是我的数据库。似乎我需要使用 iexact 但是我尝试使用它时出现错误。

这是我的代码片段。

def item_search(x): 
    item = x.column_in_database 
 
    if test__iexact = 'test' in item: 
       return 1; #this is just pseduocode for stackoverflow 
    elif 
       return 0; #this is just pseduocode for stackoverflow 

我已经尝试了多种方法,但仍然无法正常工作。

请您参考如下方法:

这很很困惑。

__iexact 是您在 Django 查询过滤器中使用的东西。 Django 在将查询发送到数据库时将其转换为相关的 SQL。它不是 Python 关键字,您不能只在语句中说 test__iexact 并期望它起作用。

在普通代码中进行不区分大小写匹配的常用方法只是将两边都转换为相同的大小写,即小写:

if 'test' in item.lower():