定义自定义经理
经常碰巧处理类似 published 字段的模型。在检索对象时几乎总是使用这种字段,这样你就会发现自己写的东西:
my_news = News.objects.filter(published=True)
太多次了。你可以使用自定义管理器来处理这些情况,以便你可以编写如下内容:
my_news = News.objects.published()
其他开发人员也更好,更容易阅读。
在 app 目录中创建一个文件 managers.py,并定义一个新的 models.Manager 类:
from django.db import models
class NewsManager(models.Manager):
    def published(self, **kwargs):
        # the method accepts **kwargs, so that it is possible to filter
        # published news
        # i.e: News.objects.published(insertion_date__gte=datetime.now)
        return self.filter(published=True, **kwargs)
通过重新定义模型类中的 objects 属性来使用此类:
from django.db import models
# import the created manager
from .managers import NewsManager
class News(models.Model):
    """ News model
    """
    insertion_date = models.DateTimeField('insertion date', auto_now_add=True)
    title = models.CharField('title', max_length=255)
    # some other fields here
    published = models.BooleanField('published')
    # assign the manager class to the objects property
    objects = NewsManager()
现在,你可以通过以下方式获取已发布的新闻:
my_news = News.objects.published()
你还可以执行更多过滤:
my_news = News.objects.published(title__icontains='meow')