Django:搜索词组中单个单词的首字母吗? [英] Django: search on first letters of individual words within phrase?

查看:108
本文介绍了Django:搜索词组中单个单词的首字母吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Author 的Django模型,其字段名为 name ,该字段未拆分直到姓氏/名字:

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)

例如,我有一个Author条目,名称为 Donald Knuth。

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

现在,我想按名称查询,在名称 c>字段。

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

所以我希望能够用' Kn '查询,并获得' Donald Knuth 回来。

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

类似的东西:

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

在Django中可能吗?

Is this possible in Django?

推荐答案

您可以使用 iregex 查找:

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)

这不是很有效,但应该可以。在MySQL上,您可以尝试利用全文搜索功能。在其他数据库上,您将需要一些额外的工具来进行高效的全文本搜索(例如 django-haystack )。

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

这篇关于Django:搜索词组中单个单词的首字母吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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