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"),
]
相关推荐
立心者01 小时前
SpringBoot中使用TOTP实现MFA(多因素认证)
java·spring boot·后端
lipku2 小时前
数字人直播开源项目LiveStream
python·开源·数字人·数字人直播
AskHarries2 小时前
SEO 页面怎么生成
后端
阿童木写作2 小时前
Python实现亚马逊商品图批量智能抠图教程
人工智能·python
爱吃牛肉的大老虎2 小时前
Rust对象之结构体,枚举,特性
开发语言·后端·rust
石榴2 小时前
NestJS 的请求到底经过了什么:装饰器、守卫、拦截器、管道与中间件如何配合
后端
axinawang2 小时前
第24课:while循环的应用
python
Gopher_HBo3 小时前
moby-client客户端
后端
三亚兴嘉装饰3 小时前
三亚服装店装修
python
小柯南敲键盘3 小时前
速卖通AI图片翻译API集成实战
人工智能·python