21Django-AttributeError: 'QuerySet' object has no attribute 'id'
阿新 • • 發佈:2021-12-17
概述:
登入使用者就可以檢視文章詳情,訪客就不能檢視文章詳情並且報錯
報錯程式碼如下:
Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. --以上程式碼基本都是確定訪客身份的-- 1 next_topic的值是: <QuerySet [<Topic: Topic object (2)>, <Topic: Topic object (3)>]> Internal Server Error: /v1/topics/qq66907360 Traceback (most recent call last): File"D:\Program Files (x86)\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Program Files (x86)\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File"D:\Program Files (x86)\Python\Python310\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "D:\Program Files (x86)\Python\Python310\lib\site-packages\django\views\generic\base.py", line 101, in dispatch return handler(request, *args, **kwargs) File"D:\PycharmProjects\linuxTangblog\topic\views.py", line 151, in get res = self.make_topic_res(author,author_topic,is_self) File "D:\PycharmProjects\linuxTangblog\topic\views.py", line 29, in make_topic_res next_id = next_topic.id if next_topic else None AttributeError: 'QuerySet' object has no attribute 'id' [17/Dec/2021 15:02:20] "GET /v1/topics/qq66907360?t_id=1 HTTP/1.1" 500 79151
排查過程:
我遍歷了一下'QuerySet'物件,發現遍歷後的資料是object物件,然後再用object取值就把值取出來了,
next_topic的值是: <QuerySet [<Topic: Topic object (2)>, <Topic: Topic object (3)>]>
next_topic = Topic.objects.filter(id__gt=author_topic.id,author=author,limit='public') for i in next_topic: print(i.id)
然後我就想,上一篇和和下一篇只要一個值,但是顯然這個queryset物件有多個值,不符合預期,然後就看程式碼發現沒有寫first()或last()這個條件
if is_self: #下一篇 next_topic = Topic.objects.filter(id__gt=author_topic.id,author=author).first() #上一篇 last_topic = Topic.objects.filter(id__lt=author_topic.id,author=author).last() else: next_topic = Topic.objects.filter(id__gt=author_topic.id,author=author,limit='public') last_topic = Topic.objects.filter(id__lt=author_topic.id,author=author,limit='public')
解決辦法:
加上first()或last()這個條件
if is_self: #下一篇 next_topic = Topic.objects.filter(id__gt=author_topic.id,author=author).first() #上一篇 last_topic = Topic.objects.filter(id__lt=author_topic.id,author=author).last() else: next_topic = Topic.objects.filter(id__gt=author_topic.id,author=author,limit='public').first() last_topic = Topic.objects.filter(id__lt=author_topic.id,author=author,limit='public').last()