Simple search in Django

后端 未结 4 1099
北海茫月
北海茫月 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:05

    You would use the __search operator. It's documented in the Django QuerySet API Reference. There's also istartswith, which does a case-insensitive starts-with search.

    Here's a working example (adapted from my own Django site):

    def search(request):
        try:
            q = request.GET['q']
            posts = BlogPost.objects.filter(title__search=q) | \
                    BlogPost.objects.filter(intro__search=q) | \
                    BlogPost.objects.filter(content__search=q)
            return render_to_response('search/results.html', {'posts':posts, 'q':q})
        except KeyError:
            return render_to_response('search/results.html')
    

    Note that __search is only available in MySQL and requires direct manipulation of the database to add the full-text index. See the MySQL documentation for additional details.

提交回复
热议问题