**#定义一个新的过滤规则,这里是过滤状态为发布的帖子**
**class PublishedManager(models.Manager):**
**def get_queryset(self):**
**return super(PublishedManager,self).get_queryset().filter(status='published')**
class Post(models.Model):
STATUS_CHOICES = (
('draft','Draft'),('published','Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,unique_for_date='publish')
author = models.ForeignKey(User,related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
**objects = models.Manager() #默认manager**
**published = PublishedManager() #新添加的manager**
class Meta:
ordering = ('publish',)
def __str__(self):
return self.title
通过python manager.py shell就可以使用新添加manager:
由于在post添加了新的内容,需要重新引入Post
>>>from blog.models import Post
>>>Post.published.all()
这样就可以过滤出所有发布状态的帖子,并且可以使用Queryset相同的方法: