Django: search on first letters of individual words within phrase?

China☆狼群 提交于 2019-12-13 14:05:52

问题


I've got a Django model called Author, with a field called name, which isn't split up into lastname/firstname:

class Author(models.Model):
    name = models.CharField(max_length=200, unique=True)

For example, I have an Author entry with name 'Donald Knuth'.

Now I'd like to query by name, using istartswith at the start of each word within the name field.

So I'd like to be able to query with 'Kn', and get 'Donald Knuth' back.

Something like:

authors = Author.objects.filter(name__word__istartswith="Kn")

Is this possible in Django?


回答1:


You can use iregex lookup:

import re

text = "Kn"
text = re.escape(text) # make sure there are not regex specials
authors = Author.objects.filter(name__iregex=r"(^|\s)%s" % text)

This isn't very efficient, but should work. On MySQL you can try taking advantage of full-text search features. On other DBs you'll need some extra tools to make an efficient full-text search (like django-haystack).




回答2:


For MySQL, [[:<:]] matches the beginning of the word.

searchStr = "Kn"
authors = Author.objects.filter(name__iregex=r"[[:<:]]{0}".format(searchStr))


来源:https://stackoverflow.com/questions/4390607/django-search-on-first-letters-of-individual-words-within-phrase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!