Django定制模型管理器

objects是检索数据库中所有对象的每个模型的默认管理器。然而,也可以为我们的模型定义自定义管理器。

比如创建一个自定义管理器来检索具有发布状态的所有帖子。关于blog的模型,可以参考

Django数据模型代码片段-CSDN博客

📌使用Post.published.all()替代Post.objects.filter(publish='published')

编辑models.py

python 复制代码
class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager,self).get_queryset().filter(status='published')

class Post(models.Model):

    ...

    objects = models.Manager()
    published = PublishedManager()

    ...

管理器的get_queryset()方法返回将要执行的QuerySet。重写此方法,以便在最终的QuerySet中包含自定义过滤器。

下面用通用视图创建blog列表。关于通用视图,更多内容请看

Django通用视图-CSDN博客

编辑views.py

python 复制代码
...
from django.views.generic import ListView
from .models import Post

class PostListView(ListView):
    queryset = Post.published.all()
    context_object_name = "posts"
    paginate_by = 3
    template_name = "blog/post/list.html"

添加URL路径

python 复制代码
from django.urls import path
from . import views

app_name = "blog"
urlpatterns = [
    path("", views.PostListView.as_view(), name="post_list"),
]
相关推荐
汤姆小白1 小时前
01-环境搭建与项目导览
人工智能·python·机器学习·numpy
To_OC5 小时前
手写 AI 编程 Agent 的命令执行工具:我被 child_process 坑出来的实战经验
后端·node.js·agent
向日的葵0067 小时前
langchain的Tools教程(三)
python·langchain·tools
逝水无殇8 小时前
C# 异常处理详解
开发语言·后端·c#
言乐69 小时前
Python实现可运行解密游戏游戏框架
python·游戏·小程序·游戏程序·关卡设计
YUS云生9 小时前
Python学习笔记·第31天:FastAPI入门——路由、路径参数、查询参数与请求体
笔记·python·学习
智写-AI9 小时前
真实有效的免费降英文AI工具服务商
人工智能·python
yuhuofei202110 小时前
【Python入门】了解掌握Python中函数的基本使用
python
考虑考虑10 小时前
Sentinel安装
java·后端·微服务
IT_陈寒10 小时前
SpringBoot自动配置失灵?你可能忘了这个关键注解
前端·人工智能·后端