Skip to content Skip to sidebar Skip to footer

Django: Search On First Letters Of Individual Words Within Phrase?

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=20

Solution 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).

Solution 2:

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

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

Post a Comment for "Django: Search On First Letters Of Individual Words Within Phrase?"