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 小时前
Python--04--数据容器(总结)
开发语言·python
架构师老Y1 小时前
008、容器化部署:Docker与Python应用打包
python·容器·架构
lifewange1 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
GreenTea2 小时前
一文搞懂Harness Engineering与Meta-Harness
前端·人工智能·后端
pluvium272 小时前
记对 xonsh shell 的使用, 脚本编写, 迁移及调优
linux·python·shell·xonsh
2401_827499992 小时前
python项目实战09-AI智能伴侣(ai_partner_5-6)
开发语言·python
PD我是你的真爱粉2 小时前
MCP 协议详解:从架构、工作流到 Python 技术栈落地
开发语言·python·架构
ZhengEnCi2 小时前
P2G-Python字符串方法完全指南-split、join、strip、replace的Python编程利器
python
是小蟹呀^2 小时前
【总结】LangChain中工具的使用
python·langchain·agent·tool
宝贝儿好2 小时前
【LLM】第二章:文本表示:词袋模型、小案例:基于文本的推荐系统(酒店推荐)
人工智能·python·深度学习·神经网络·自然语言处理·机器人·语音识别