简体   繁体   English

Django ORM拆分名称并搜索

[英]Django ORM split the name and search

I have a model named Suburb. 我有一个名为Suburb的模型。 with one field called name. 与一个名为名称的字段。

name of the suburb can be mulitple words say "East west country". 郊区的名称可以用多个单词说“东西方国家”。 I want all the records whose part words starts with given string. 我想要所有单词以给定字符串开头的记录。

class Suburb(models.Model):
    name = models.CharField(_('suburb name'), blank=False, max_length=200)

search_string = "we"

# Give me all records whose part words starts with "search_string"

Suburb.objects.filter(...) # with ignore case ??? 

Example 
----------
1) "East west one"
2) "We east two"
3) "North south three"

result should be 1) and 2) 

I have a pythonic solution. 我有一个pythonic解决方案。 but its performance is quite bad. 但是它的性能还是很差的。

DB = MYSQL 数据库= MYSQL

Thanks in advance 提前致谢

Best Django solution without engaging Full Text Search or search engine would be to use icontains 不使用全文搜索或搜索引擎的最佳Django解决方案是使用icontains

So in your case 所以你的情况

Suburb.objects.filter(name__icontains=search_string)

Edit : for start of each word use iregex: 编辑 :对于每个单词的开头,请使用iregex:

For mysql [[:<:]] signifies start of word 对于mysql [[:<:]]表示单词的开头

So something like this would be solution 所以像这样的解决方案

Suburb.objects.filter.(name__iregex=r'[[:<:]]' + re.escape(search_string)

Also note that following solution doesn't scale as there is wildcard regex 另请注意,以下解决方案无法扩展,因为存在通配符正则表达式

You can use a combination of istartswith and icontains with the Q object 您可以将istartswithicontainsQ对象结合使用

search_string = 'we'
Sample.objects.filter(Q(name__istartswith=search_string) | Q(name__icontains=' ' + search_string))

With this solution I am assuming that your words are always delimited by a space character. 通过这种解决方案,我假设您的单词始终以空格字符分隔。

Using the iregex filter as another option which could be used but I have not created an example for. 使用iregex过滤器作为可以使用的另一个选项,但我尚未为其创建示例。

Search by part word: 按零件词搜索:

search_string = "we"
Suburb.objects.filter(name__icontains = search_string)
    Result:
    1) "East west one"
    2) "We east two"

Search from starting word: 从起始词搜索:

search_string = "we"
Suburb.objects.filter(name__startswith = search_string)
    Result:
    2) "We east two"

Search exact work: 搜索确切的工作:

search_string = "we"
Suburb.objects.filter(name__iexact = search_string)
Result: no result
search_string = "We east two"
Result:
2) "We east two"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM