创建模型管理器

时间:2016-01-14 08:09:59

标签: django django-models

我的博客应用程序的models.py是这样的 -

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

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()
    published = PublishedManager() 


    class Meta:
    ordering = ('-publish',)

    def __str__(self):
    return self.title

当我在shell中运行Post.published.filter(title__startswith='Who')

它给我的shell充满了这样的错误 -

Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/django/core/management       
/commands/shell.py", line 77, in handle_noargs
self.run_shell(shell=interface)
File "/usr/local/lib/python3.4/dist-packages/django/core/management    
/commands/shell.py", line 65, in run_shell
raise ImportError
ImportError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3.4/code.py", line 90, in runcode
exec(code, self.locals)
File "<console>", line 1, in <module>
AttributeError: type object 'Post' has no attribute 'published'

对此感到困惑。如果还有另一种方式,请帮助我。 给bith ImportError以及AttributeError 我是否需要在shell中导入更多内容。 已经导入

from django.contrib.auth.models import User
from blog.models import Post

在我的shell中

1 个答案:

答案 0 :(得分:0)

代码看起来不错,因此在添加经理之前,您的shell很可能没有启动。 重新启动shell,然后重试。