Django:如何在模型字段值和过滤器中去除空格? [英] Django: How to strip out spaces in the model field value and filter?

查看:95
本文介绍了Django:如何在模型字段值和过滤器中去除空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

name ="New York","New Jersey","New America"等

name = "New York", "New Jersey", "New America" etc

通过使用以下查询,我将获得字符串包含 New

By using the following query I will get all the results with the string contains New

City.objects.filter(name__icontains="New") # Perfect

但是如何找到纽约而又不增加纽约之间的距离

But How to find New York with out adding the space between new york

City.objects.filter(name__icontains="NewYork") # Not getting New York

如何过滤?请让我知道您的意见

How to filter ? Please let me know your views

推荐答案

无需剥离任何内容,正则表达式即可完成工作

No need to strip anything, regex would do the job

City.objects.filter(name__regex=r'(?i)new[\s\w]+')

(?i)使表达式不区分大小写,尽管您也可以简单地使用 __ iregex

(?i) makes the expression case insensitive, although you could also simply use __iregex

https://docs.djangoproject.com/en/dev/ref/models/querysets/#regex

这篇关于Django:如何在模型字段值和过滤器中去除空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆