Django AttributeError Model对象没有属性'filter'

时间:2014-03-04 20:31:19

标签: python django

我正在尝试使用Django创建自己的博客。我的目的是展示一篇从DetailView扩展而来的文章。 为了避免任何麻烦,我试图将文章分类为其发布日期。文章的网址是这样的(其中pk对应于文章的标题):

r'articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<pk>[\w-]+)/$'

在我看来,我想这样做:

def get_queryset(self):
    year = self.kwargs.get("year", None)
    month = self.kwargs.get("month", None)
    day = self.kwargs.get("day", None)

    publication_date = year + "-" + month + "-" + day

    return Article.objects.get(created_at__startswith=publication_date, slug=self.kwargs.get("pk", None))

但它不起作用,我不明白...... 事实上,当我这样做时它会起作用:

return Article.objects.filter(created_at__startswith=publication_date, slug=self.kwargs.get("pk", None))

但它返回一个QuerySet,我只想要一篇文章! ([0]返回相同的错误)

这是错误:

AttributeError at /articles/2015/03/04/nouveau-site/
'Article' object has no attribute 'filter'
Django Version: 1.6.2
Exception Location: C:\Python27\lib\site-packages\django\views\generic\detail.py in get_object, line 37
Python Version: 2.7.6

完整的追溯:

Environment:


Request Method: GET
Request URL: http://localhost:8000/articles/2015/03/04/nouveau-site/

Django Version: 1.6.2
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'groups',
 'posts',
 'users')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\base.py" in view
  69.             return self.dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\base.py" in dispatch
  87.         return handler(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\detail.py" in get
  110.         self.object = self.get_object()
File "C:\Python27\lib\site-packages\django\views\generic\detail.py" in get_object
  37.             queryset = queryset.filter(pk=pk)

Exception Type: AttributeError at /articles/2015/03/04/nouveau-site/
Exception Value: 'Article' object has no attribute 'filter'

提前致谢!

1 个答案:

答案 0 :(得分:11)

def get_queryset(self):
    ...

    return Article.objects.filter(created_at__startswith=publication_date, slug=self.kwargs.get("pk", None))

因为get_queryset必须返回QuerySet对象,而不是模型一