简单的搜索Django [英] Simple search in Django

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

问题描述

我有一个非常简单的博客应用程序,我想添加一个非常简单的搜索功能。

I've got a really simple blog application and I want to add a really simple search feature to it.

我的模型有3个关键字段。 / p>

There are 3 key fields to my model.

class BlogPost(models.Model):
    title = models.CharField(max_length=100) # the title
    intro = models.TextField(blank=True, null=True) # an extract
    content = models.TextField(blank=True, null=True) # full post

我不需要Google。我不想搜索评论(无论如何仍在Disqus举行)。我只想要一个日期排名的关键字过滤的帖子。

I don't need a Google. I don't want to search comments (which are held on Disqus anyway). I just want a date-ranked, keyword filtered set of posts.

我在Google上找到的一些形式的django和搜索的所有东西都回到了可怕的复杂Haystack +后端解决方案。我不需要所有这些。我不想在低使用率功能上吃掉更多的资源(以前在我移植到Django之前有一个搜索框,每月可能有4次搜索)。

Everything I find on Google for some form of "django" and "search" comes back with hideously complicated Haystack+backend solutions. I don't need all that. I don't want to eat up more resources on a low-usage feature (I used to have a search box before I ported to Django and it had perhaps 4 searches a month).

我在这里花时间问问(而不仅仅是写一个凌乱的小脚本)的原因是这个已经存在于管理员中。您可以设置要搜索的列,然后只是搜索,它只是工作。

The reason I'm taking time to ask on here (rather than just writing a messy little script) is this already exists in the admin. You can set the columns to search on and then just search and it "just works".

有没有办法在管理员提供的搜索和拉

Is there some way of getting a handle on the admin-provided search and pulling it into my user-facing app?

推荐答案

如果你想要一个非常简单的搜索,你可以使用 icontains 查找和 Q object

If you want a really simple search you can use icontains lookup and Q object:

from django.db.models import Q
results = BlogPost.objects.filter(Q(title__icontains=your_search_query) | Q(intro__icontains=your_search_query) | Q(content__icontains=your_search_query))


$ b你还应该注意,干草堆不一定要非常复杂。

You should also note that Haystack doesn't have to be "hideously complicated". You can set up haystack with Whoosh backend in less then 15 minutes.

更新2016:在1.10版本中,Django添加了全文搜索支持(仅PostgreSQL)。使用新模块的原始问题的答案可能如下所示:

Update 2016: In version 1.10 Django added a full text search support (PostgreSQL only). An answer to the original question using the new module might look something like this:

from django.contrib.postgres.search import SearchVector

results = BlogPost.objects.annotate(
    search=SearchVector('title', 'intro', 'content'),
).filter(search=your_search_query)

新的全文搜索模块包含更多功能(例如通过相关性排序),您可以< a href =https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/search/ =nofollow noreferrer>请阅读文档中的相关信息。

The new full text search module contains a lot more features (for example sorting by relevancy), you can read about them in the documentation.

这篇关于简单的搜索Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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