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 小时前
Cursor 模型的强度实测排行
前端·人工智能·后端
YCOSA20251 小时前
系统工具使用检测.exe (仅供娱乐)
python·microsoft
2601_962295332 小时前
如何python实现网页的自动化
python·selenium·beautifulsoup·requests·网页自动化
ofoxcoding2 小时前
GPT Image 2.5 API 实战:Python 调用实现图片生成与编辑
人工智能·python·gpt·ai
GoGeekBaird2 小时前
从「跑完即销毁」到「用完再销毁」:云沙箱的一次进化
后端·github·ai编程
张小姐的猫2 小时前
【AI大模型接入SDK】 —— Gemini接入封装
android·数据结构·数据库·c++·人工智能·python
孫治AllenSun2 小时前
【LangChain4J-09】开发学习知识点
spring boot·后端·学习
Elastic 中国社区官方博客3 小时前
Elasticsearch Python DSL 客户端开发
大数据·数据库·python·elasticsearch·搜索引擎·全文检索
lisin-lee-cooper3 小时前
简单聊聊 Spring 框架源码
java·后端·spring
复方金银花颗粒3 小时前
reactor和proactor的好处和坏处。为什么要用reactor而不用 proactor?
后端·信号处理