【后端】【django】【进阶】自定义管理器——封装常用查询

1. 自定义管理器的作用

Django 的 models.Manager 允许自定义查询逻辑,让你更方便地封装常用查询,提高代码复用性。

在你的示例中:

  • objects = models.Manager() 是 Django 默认的管理器,返回所有数据。
  • published = PublishedManager() 是自定义的管理器,只返回已发布的文章is_published=True)。
  • 这样可以通过 Article.published.all() 快速获取已发布的文章,而不影响 Article.objects.all() 返回所有文章。

2. 代码解析

python 复制代码
class PublishedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(is_published=True)

(1)get_queryset() 方法

  • 作用 :重写 get_queryset(),修改默认查询集(QuerySet)。
  • 原理super().get_queryset() 获取原始 QuerySet,然后 .filter(is_published=True) 让它只返回 is_published=True 的数据。

3. 使用示例

python 复制代码
# 创建文章
Article.objects.create(title="草稿文章", content="这是一篇草稿", is_published=False)
Article.objects.create(title="已发布文章", content="这是一篇已发布的文章", is_published=True)

# 查询所有文章
print(Article.objects.all())  
# 输出: <QuerySet [<Article: 草稿文章>, <Article: 已发布文章>]>

# 只查询已发布的文章
print(Article.published.all())  
# 输出: <QuerySet [<Article: 已发布文章>]>
  • Article.objects.all() 返回所有文章。
  • Article.published.all() 自动过滤掉未发布的文章

4. 其他常见用法

(1)添加自定义方法

可以在 PublishedManager 里添加更多自定义方法,比如查询最近发布的文章:

python 复制代码
class PublishedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(is_published=True)

    def recent(self, days=7):
        from django.utils.timezone import now
        return self.get_queryset().filter(created_at__gte=now() - timedelta(days=days))

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    is_published = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = models.Manager()  # 默认管理器
    published = PublishedManager()  # 只返回已发布的文章
使用方法
python 复制代码
# 查询最近 7 天发布的文章
Article.published.recent()

(2)防止 objects 被覆盖

如果 objects 只使用 PublishedManager,就无法查询未发布的文章

python 复制代码
class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    is_published = models.BooleanField(default=False)

    objects = PublishedManager()  # 这样 `objects.all()` 也只返回已发布的文章

如果要查询所有文章(包括未发布的),最好保留 objects = models.Manager(),这样:

  • Article.objects.all() 获取所有文章
  • Article.published.all() 只获取已发布的文章

5. 总结

功能 默认管理器 objects 自定义管理器 published
返回所有数据 Article.objects.all()
只返回已发布数据 Article.published.all()
可以扩展更多方法 Article.published.recent()

💡 适用于哪些场景?

  • 需要频繁筛选某些特定数据(如已发布文章、活跃用户)。
  • 让查询更语义化 ,避免重复 filter()
  • 避免 objects 被污染,保留所有数据的访问能力
相关推荐
jiayou641 天前
KingbaseES 表级与列级加密完全指南
数据库·后端
GBASE2 天前
G术时刻 |GBase 8s数据库事务并发控制之封锁技术介绍(下)
数据库
xiezhr2 天前
逛GitHub发现了一款免费的带AI功能的数据库管理工具
数据库·ai编程·dba
吃糖的小孩3 天前
给 QQ AI 机器人设计“可控记忆”:会话摘要、手动长期记忆与角色卡边界
数据库
笃行3504 天前
金仓数据库数据安全双防线:静态存储加密与传输加密实战
数据库
笃行3504 天前
金仓数据库物理备份实战:sys_rman 全流程演练与误覆盖抢救
数据库
笃行3504 天前
金仓数据库逻辑备份实战:从全库导出到 Schema 替换的完整闭环
数据库
SelectDB5 天前
阶跃星辰基于 SelectDB 构建 PB 级 Agent 可观测平台
大数据·数据库·aigc
这个DBA有点耶5 天前
GROUP BY优化全解:如何写出既不丢数据又飞快的分组查询
数据库·mysql·架构