orm 在查询时默认不区分大小写,使用以下关键字时会区分大小写
contains/icontains
- contains: 进行大小写敏感的判断,某个字符串是否包含在指定的字段中,在被翻译成“SQL”语句的时候,会使用“like binary”, 而“like binary”就是使用大小写敏感进行判断。
- icontains: 进行大小写不敏感的判断,某个字符串是否包含在指定的字段中,在被翻译成“SQL”语句的时候,会使用“like”, 而“like”就是使用大小写不敏感进行判断。其中icontains前面的i指的就是ignore(忽略)。
1 2 3 4 5 6 7
| obj = Bucket.objects.filter(name__icontains="collect") print(obj.query) obj = Bucket.objects.filter(name__contains="collect") print(obj.query)
# SELECT ... FROM `bucket` WHERE `bucket`.`name` LIKE %collect% # SELECT ... FROM `bucket` WHERE `bucket`.`name` LIKE BINARY %collect%
|
startswith/endswith/ istartswith/iendswith
- startswith:大小写敏感的判断某个字段的值是否以某个值开始的
- istartswith: 大小写不敏感的判断某个字段的值是否以某个值开始的
- endswith: 大小写敏感的判断某个字段的值中是否含有某个值开始
- iendswith:不区分大小写判断某个字段的值中是否含有某个值
1 2 3 4 5 6 7 8 9 10 11 12
| obj = Bucket.objects.filter(name__startswith="collect") print(obj.query) obj = Bucket.objects.filter(name__endswith="collect") print(obj.query) obj = Bucket.objects.filter(name__istartswith="collect") print(obj.query) obj = Bucket.objects.filter(name__iendswith="collect")
# SELECT ... FROM `bucket` WHERE `bucket`.`name` LIKE BINARY collect% # SELECT ... FROM `bucket` WHERE `bucket`.`name` LIKE BINARY %collect # SELECT ... FROM `bucket` WHERE `bucket`.`name` LIKE collect% # SELECT ... FROM `bucket` WHERE `bucket`.`name` LIKE %collect
|
regex
- 区分大小写的正则表达式匹配
1 2 3 4
| obj = Bucket.objects.filter(name__regex="collect") print(obj.query)
# SELECT ... FROM `bucket` WHERE `bucket`.`name` REGEXP BINARY collect
|
- 还可以使用原生 extra
1 2 3 4 5
| bucket_name = ("111", "222") obj = Bucket.objects.extra(where=[f"binary name in {tuple(bucket_name)}"]).all() print(obj.query)
# SELECT ... FROM `bucket` WHERE (binary name in ('111', '222'))
|