Python 获取在Django筛选器中小写/无空格名称等于小写/无空格参数的对象
我想获得所有Python 获取在Django筛选器中小写/无空格名称等于小写/无空格参数的对象,python,regex,django,filter,Python,Regex,Django,Filter,我想获得所有产品,其中名称字段的无空格/小写版本等于Django中输入产品名称参数的无空格/小写版本。我该怎么做 伪代码 def get_or_add_product(input_product_name): return Product.objects.filter(where no-space/lowercase version of name == input_product_name.strip().lower()) ##以防仅从开头和结尾删除空格 Product.object
产品
,其中名称
字段的无空格/小写版本等于Django中输入产品名称
参数的无空格/小写版本。我该怎么做
伪代码
def get_or_add_product(input_product_name):
return Product.objects.filter(where no-space/lowercase version of name == input_product_name.strip().lower())
##以防仅从开头和结尾删除空格
Product.objects.extra(
其中=[“下(修剪(名称))=%s”],
参数=[input_product_name.strip().lower()]
)
##以防从字符串中的任何位置删除空格
Product.objects.extra(
其中=[“下部(替换(名称,,”)=%s”],
参数=[input_product_name.strip().lower()]
)
###以防仅从开头和结尾删除空格
Product.objects.extra(
其中=[“下(修剪(名称))=%s”],
参数=[input_product_name.strip().lower()]
)
##以防从字符串中的任何位置删除空格
Product.objects.extra(
其中=[“下部(替换(名称,,”)=%s”],
参数=[input_product_name.strip().lower()]
)
您可以使用Django的queryset和它的 例如,在您的情况下:
从django.db.models导入值
从django.db.models.functions导入较低版本,替换
def get_product(输入_product_名称):
input_product_name=input_product_name.lower().替换(“”,“”)
返回Product.objects.annotate(
lowered_nospace_name=Lower(替换('name',Value(''),Value('')))
).过滤器(
降低的\u nospace\u name=输入\u产品\u名称
)
注意,SQL的“代码>Times”(<代码)>和Python的<代码>条目()/代码>只在字符串的开头和结尾去除空白。例如,
strip('hello')=='hello'
安全说明
def get_or_add_product(input_product_name):
return Product.objects.filter(where no-space/lowercase version of name == input_product_name.strip().lower())
编写原始SQL在您的情况下会有所帮助,但是,如果无法使用Django QuerySet方法表达查询,请将其作为最后的手段。
extra()
例如,在您的情况下:
从django.db.models导入值
从django.db.models.functions导入较低版本,替换
def get_product(输入_product_名称):
input_product_name=input_product_name.lower().替换(“”,“”)
返回Product.objects.annotate(
lowered_nospace_name=Lower(替换('name',Value(''),Value('')))
).过滤器(
降低的\u nospace\u name=输入\u产品\u名称
)
注意,SQL的“代码>Times”(<代码)>和Python的<代码>条目()/代码>只在字符串的开头和结尾去除空白。例如,
strip('hello')=='hello'
安全说明
def get_or_add_product(input_product_name):
return Product.objects.filter(where no-space/lowercase version of name == input_product_name.strip().lower())
编写原始SQL在您的情况下会有所帮助,但是,如果无法使用Django QuerySet方法表达查询,请将其作为最后的手段。extra()
我知道我可以用.lower().strip()
降低/去除输入产品名称
,但我如何将其应用于模型名称
字段?SQL格式:“WHERE lower(REPLACE(name),,”)={}。格式(input\u product\u name.strip().lower())
我在示例中输入了一个错误upper
应该是lower
你知道为什么当input\u product\u name
='iphonex'时它不会返回'iphonex'吗?我想我找到了原因:我需要使用replace
而不是trim
嗯,我的编辑返回:无法获取
的repr。知道为什么吗?好的,我知道了,我忘了逃避引用我在我的例子中打错了upper
应该是lower
你知道为什么当input\u product\u name
='iphonex'时它不会返回'iphonex'吗?我想我找到了原因:我需要使用replace
而不是trim
嗯,我的编辑返回:无法获取
的repr。知道为什么吗?知道了,我忘了逃过引用