gpt4 book ai didi

python - Django AttributeError 模型对象没有属性 'filter'

转载 作者:太空狗 更新时间:2023-10-29 20:17:01 25 4
gpt4 key购买 nike

我正在尝试使用 Django 创建自己的博客。我有一个 View 来显示一篇从 DetailView 扩展而来的文章。为避免 slug 带来任何麻烦,我尝试根据文章的发布日期对文章进行分类。文章的 url 是这样的(其中 pk 对应于文章的 slug):

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'

提前致谢!

最佳答案

def get_queryset(self):
...

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

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

关于python - Django AttributeError 模型对象没有属性 'filter',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22182372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com