1. 程式人生 > 其它 >18Django-raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type UserProfile is not JSON serializable

18Django-raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type UserProfile is not JSON serializable

我再編寫獲取文章列表路基的時候,訪問介面地址報錯(127.0.0.1:8000/v1/topics/qq66907360

TypeError at /v1/topics/qq66907360
Object of type UserProfile is not JSON serializable
Request Method:    GET
Request URL:    http://127.0.0.1:8000/v1/topics/qq66907360
Django Version:    4.0
Exception Type:    TypeError
Exception Value:    
Object of type UserProfile 
is not JSON serializable Exception Location: D:\Program Files (x86)\Python\Python310\lib\json\encoder.py, line 179, in default Python Executable: D:\Program Files (x86)\Python\Python310\python.exe Python Version: 3.10.0 Python Path: ['D:\\PycharmProjects\\linuxTangblog', 'D:\\PycharmProjects\\linuxTangblog
', 'D:\\PycharmProjects\\linuxTangblog', 'D:\\Program Files\\JetBrains\\PyCharm ' '2020.3.3\\plugins\\python\\helpers\\pycharm_display', 'D:\\Program Files (x86)\\Python\\Python310\\python310.zip', 'D:\\Program Files (x86)\\Python\\Python310\\DLLs', 'D:\\Program Files (x86)\\Python\\Python310\\lib',
'D:\\Program Files (x86)\\Python\\Python310', 'C:\\Users\\66907\\AppData\\Roaming\\Python\\Python310\\site-packages', 'D:\\Program Files (x86)\\Python\\Python310\\lib\\site-packages', 'D:\\Program Files\\JetBrains\\PyCharm ' '2020.3.3\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Thu, 16 Dec 2021 18:14:13 +0800

經排查發現問題出在了這裡:

def make_topics_res(self,author,author_topics):
        res = {'code':200,'data':{}}
        topics_res = []
        #遍歷出每一篇文章
        for topic in author_topics:
            #組織資料
            #{‘id’:1, ‘title’:’A’, ‘category’:’python’, ‘created_time’:’2021-12-15 21:07:20’, ‘introduce’:’AAA’, ‘author’:’qq66907360’}
            d={}
            d['id'] = topic.id
            d['title'] = topic.title
            d['category'] = topic.category
            d['create_time'] = topic.create_time.strftime("%Y-%m-%d %H:%M:%S")
            d['introduce'] = topic.introduce
            d['author'] = topic.author #author是文章模型類裡的一個外來鍵,是物件,這裡直接這樣寫是獲取不到作者名的,應該寫成:d['author'] = topic.author.username