Yann Bertrand Yann Bertrand - 2 years ago 188
Python Question

Django AttributeError Model object has no attribute 'filter'

I'm trying to do my own blog using Django. I have a view to show an article which is extended from DetailView.
To avoid any trouble with slugs, I'm trying to classify the articles with its date of publication. The url for an article is like so (where pk correspond to the slug of the article):


In my view I want to do this:

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))

But it doesn't work and I don't get it...
In fact it works when I do this:

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

But it returns a QuerySet and I just want one article! ([0] returns the same error)

Here is the error:

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

And the full traceback:


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:
Installed Middleware:

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'

Thanks in advance!

Answer Source
def get_queryset(self):

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

Because get_queryset must return QuerySet object, not model one

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download