在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页面中。