在Django中實現搜索功能的一種常見方法是使用Django內置的模糊搜索功能。具體步驟如下:
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
from django.shortcuts import render
from .models import Article
def search(request):
query = request.GET.get('q')
articles = Article.objects.filter(title__icontains=query) | Article.objects.filter(content__icontains=query)
return render(request, 'search_results.html', {'articles': articles})
<!DOCTYPE html>
<html>
<head>
<title>Search Results</title>
</head>
<body>
<h1>Search Results</h1>
{% for article in articles %}
<h2>{{ article.title }}</h2>
<p>{{ article.content }}</p>
{% empty %}
<p>No results found.</p>
{% endfor %}
</body>
</html>
from django.urls import path
from .views import search
urlpatterns = [
path('search/', search, name='search'),
]
完成以上步驟后,用戶可以在搜索框中輸入關鍵字進行搜索,Django會根據標題和內容字段進行模糊匹配,并將搜索結果顯示在search_results.html頁面中。