1
我的博客應用的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')
它給了我充分殼的錯誤這樣的 -
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在添加管理器之前沒有啓動?即當你重新打開你的shell時問題是否會持續存在? – SaeX
另外,請注意'class Meta'和'def __str__'的縮進。 – SaeX
謝謝,忘了重啓shell。 –