【发布时间】:2016-01-25 01:30:23
【问题描述】:
我正在关注有关使用 cutom 模型管理器的 django 教程,但无法弄清楚为什么这不起作用。
我正在尝试使用自定义模型管理器来过滤仅在数据库中标记为活动的帖子,因此它不会显示尚未完成的帖子。
模型管理器
class PostManager(models.Manager):
def get_query_set(self):
return super(PostManager, self).get_query_set().filter(is_active=True)
型号
class Post(models.Model):
title = models.CharField(max_length = 100)
description = models.TextField(max_length = 500)
body = models.TextField(blank = True)
created = models.DateTimeField(auto_now_add = True)
modified = models.DateTimeField(auto_now_add = True)
is_active = models.BooleanField(default = 1)
allow_comments = models.BooleanField(default = 1)
category= models.ForeignKey(Category)
creator = models.ForeignKey(User)
slug = models.SlugField(unique = True)
active = PostManager() #Gets just the active posts
objects = models.Manager()
然后我尝试使用 posts= Post.active.all() 过滤活动帖子
现在,如果我将其更改为 posts = Post.active.filter(is_active=True) 它可以工作并仅过滤活动帖子,但我可以在没有自定义管理器的情况下这样做。不,了解这里发生了什么。
【问题讨论】:
标签: python django python-3.x django-models django-admin