我想获取所有products
,其中name
字段的无空格/小写版本等于Django中input_product_name
参数的无空格/小写版本。我该怎么办?
伪代码
def get_or_add_product(input_product_name):
return Product.objects.filter(where no-space/lowercase version of name == input_product_name.strip().lower())
答案 0 :(得分:4)
您可以将Django的查询集annotate和expression及其Database Functions一起使用。
例如,在您的情况下:
s3://<path-to-file>
请注意,SQL的from django.db.models import Value
from django.db.models.functions import Lower, Replace
def get_product(input_product_name):
input_product_name = input_product_name.lower().replace(' ', '')
return Product.objects.annotate(
lowered_nospace_name=Lower(Replace('name', Value(' '), Value('')))
).filter(
lowered_nospace_name=input_product_name
)
和Python的Trim()
仅在字符串的开头和结尾去除空格。例如,strip()
。
安全说明
编写原始SQL可以帮助解决您的问题,但是,如果您无法使用Django QuerySet方法来表达查询,请仅将其用作最后的选择。 The Django team will deprecate将来会strip(' hello ') == 'hello'
功能,因为它可能会受到SQL Injection攻击。
答案 1 :(得分:2)
## In-case spaces are to removed from beginning and end only
Product.objects.extra(
where=["LOWER(TRIM(name)) = %s"],
params=[input_product_name.strip().lower()]
)
## In-case spaces are to removed from everywhere in string
Product.objects.extra(
where=["LOWER(REPLACE(name,' ','')) = %s"],
params=[input_product_name.strip().lower()]
)