18Django-raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of ty

我再编写获取文章列表路基的时候,访问接口地址报错(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


 

上一篇:CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/pytorch/linux-64/pyto


下一篇:node入门