Simple search in Django

后端 未结 4 1167
北海茫月
北海茫月 2021-01-30 17:36

I have a really simple blog application and I want to add a really simple search feature to it.

There are 3 key fields to my model.

class BlogPost(models         


        
4条回答
  •  你的背包
    2021-01-30 18:11

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

    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.

    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)
    

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

提交回复
热议问题