蓝色天空网mbsky.com · 知识 · 实践 · 创造Django · 本地阅读预览
教程 / Python / 数据科学 / Django

组合 Django 博客的分类筛选与关键词搜索

用浏览器真实提交 GET 表单,并在 SQLite 检查关键词、分类、查询参数编码与查找方式。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

从查询参数取得两类条件

分类和关键词由 URL 查询字符串传入,Django 将其解码为 QueryDict。用 request.GET.get 取值并设置缺省值。重复键的 get 返回最后一项,需要全部值时才用 getlist。本站去掉首尾空白并限定两种输入的长度。

查询从公开文章开始。有分类时,通过 category__slug 跨外键匹配。有关键词时,把标题和摘要的 icontains 用 Q 对象按 OR 组合,再与分类及公开条件按 AND 合并。查询仍可继续按模型顺序和时间筛选。

模糊查找和大小写规则由数据库决定。这里在 SQLite 对 ASCII 字母实测 contains 与 icontains 都命中两种大小写,切换驱动应重新观察。精确匹配、区间边界和分类列表分别取实际结果。

用真实 GET 表单保留筛选条件

GET 表单在已有分类时用隐藏字段保留分类。分类链接使用 Django 的 querystring 标签更新 category,并移除旧分页。HTML 自动转义和 URL 查询编码解决的是不同问题,直接把关键词插入地址无法正确表示加号、井号或 &。

输入含中文、&、井号、加号和百分号的关键词。本机在浏览器实际提交后读取返回 URL 的解码结果,选 Django 分类仍能匹配,改选 Python 后显示空结果。

在浏览器中保留编码关键词并选中 Django 分类
本站实测截图。搜索保留特殊字符,选中的分类和当前结果同时显示。

清除关键词链接保留分类,所有分类链接保留关键词,清除全部回到无条件首页。结果统计与当前查询一致。分类选中状态有 aria-current 和不同背景,输入框保留可见焦点。

SQLite 中六类 ORM 查找

查找方式作用本地观察与条件
field__exact比较一个完整值在默认二进制比较的测试列,SeaToken 只命中同大小写夹具。
field__iexact不区分大小写的精确查找用 SEATOKEN 命中大小写不同的两条 ASCII 记录。
field__contains包含指定文本在本机 SQLite 的 ASCII 夹具中与 icontains 同样命中两条。
field__icontains不区分大小写的包含查找匹配测试标题及摘要两个分支,非 ASCII 表现依赖驱动和排序规则。
field__gte / field__lte下界大于等于,上界小于等于将两边界设成同一个有时区时间,恰好命中边界上的记录。
field__in=[...]判断值是否在给定集合对 category_id 传已选主键列表,返回对应分类记录。

真实提交关键词并切换分类

python · 阅读源码
from django.contrib import messages
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponseBadRequest,JsonResponse
from django.shortcuts import get_object_or_404,redirect,render
from django.urls import reverse
from django.views.decorators.http import require_POST

from .forms import RegisterForm
from .models import Category,Post


def published_posts():
    return Post.objects.filter(status=Post.Status.PUBLIC).select_related("category")


def criteria(request):
    return request.GET.get("category","").strip()[:50],request.GET.get("q","").strip()[:120]


def filtered_posts(category,keyword):
    posts=published_posts()
    if category:
        posts=posts.filter(category__slug=category)
    if keyword:
        posts=posts.filter(Q(title__icontains=keyword)|Q(summary__icontains=keyword))
    return posts


def saved_ids(request):
    if not request.user.is_authenticated:
        return set()
    return set(request.user.favorite_posts.values_list("pk",flat=True))


def list_context(request,category,keyword,route):
    return {"title":"海岸笔记归档","categories":Category.objects.order_by("name"),
            "category":category,"keyword":keyword,"list_path":reverse(route),"saved_ids":saved_ids(request)}


def index(request):
    category,keyword=criteria(request)
    posts=list(filtered_posts(category,keyword))
    data=list_context(request,category,keyword,"blog:index_function")
    return render(request,"blog/index.html",{**data,"posts":posts,"result_count":len(posts)})


def post_detail(request,pk):
    post=get_object_or_404(published_posts(),pk=pk)
    return render(request,"blog/detail.html",{"post":post,"saved_ids":saved_ids(request)})


def register(request):
    if request.user.is_authenticated:
        return redirect("blog:index")
    form=RegisterForm(request.POST if request.method=="POST" else None)
    if request.method=="POST" and form.is_valid():
        user=form.save()
        login(request,user)
        messages.success(request,"账号已建立,欢迎回来。")
        return redirect("blog:index")
    return render(request,"blog/register.html",{"form":form})


@login_required
@require_POST
def set_favorite(request,pk):
    post=get_object_or_404(published_posts(),pk=pk)
    action=request.POST.get("action")
    if action=="add":
        post.favorites.add(request.user)
    elif action=="remove":
        post.favorites.remove(request.user)
    else:
        return HttpResponseBadRequest("Unknown favorite action.")
    messages.info(request,"收藏状态已更新。")
    return redirect(post.get_absolute_url())


@login_required
def favorites(request):
    posts=published_posts().filter(favorites=request.user)
    return render(request,"blog/favorites.html",{"posts":posts})


def probe(request,value):
    return JsonResponse({"type":type(value).__name__,"value":str(value)})
预期结果 · 待实际运行核验
  • 带保留字符的关键词能往返。Django 分类匹配一条,Python 分类为空,清除关键词后恢复当前分类的两条记录。
真实提交关键词并切换分类

所需环境:CPython 3.12.14、Django 5.2.19、SQLite、Edge

当前源码 SHA256:9e85e955e42f8166a15969a388725744b0b9b62d443578e8389d8070725de089

下载本站示例源码

完整开发工程

解压后按 README 选择依赖。完整工程包含路由、数据模型、测试、文档资源和启动配置。

下载本站海岸笔记交互工程

所需环境:CPython 3.12.14、Django 5.2.19、SQLite、Edge

ZIP SHA256:ebea3295216566d90f9bdd4d08a9031064a9d3bd4aff5afa5a50d2f5c61c3af5

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

打开 /function/,提交本章关键词,切换分类后分别尝试清除关键词和清除全部。

展开参考解答

选择分类会保留搜索值,清除关键词保留分类,清除全部恢复六条公开记录。

规范与官方依据