我有一个名为 Author
的 Django 模型,其中有一个名为 name
的字段,它没有拆分为姓氏/名字:
class Author(models.Model):
name = models.CharField(max_length=200, unique=True)
例如,我有一个名为“Donald Knuth”的作者条目。
现在我想按名称查询,在 name
字段中的每个单词的开头使用 istartswith 。
所以我希望能够使用“Kn
”进行查询,并返回“Donald Knuth
”。
类似于:
authors = Author.objects.filter(name__word__istartswith="Kn")
这在 Django 中可行吗?
最佳答案
您可以使用 iregex
查找:
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)
这不是很有效,但应该可以。在 MySQL 上,您可以尝试利用 full-text search features .在其他数据库上,您需要一些额外的工具来进行高效的全文搜索(例如 django-haystack )。
关于python - Django:搜索短语中单个单词的首字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4390607/