TypeError:“TopicSerializer”类型的对象不是 JSON 可序列化的 Django

Posted

技术标签:

【中文标题】TypeError:“TopicSerializer”类型的对象不是 JSON 可序列化的 Django【英文标题】:TypeError: Object of type 'TopicSerializer' is not JSON serializable Django 【发布时间】:2020-12-13 19:47:09 【问题描述】:

大家好,我在获得 API 响应时遇到了这个问题。我正在使用django==2.1.7。下面我添加我的代码 sn-p

models.py

模型包含主题名称(en,bn)、taglist(string)和Bucket_id或topic_id


class Topics(models.Model):
    id = models.AutoField(primary_key=True)
    name_en = models.CharField(max_length=70, blank=False, default='')
    name_bn = models.CharField(max_length=70, blank=False, default='')
    tags = models.TextField(blank=False, default='')
    bucket_id = models.IntegerField()


    def set_tags(self, x):
        self.tags = json.dumps(x)

    def get_tags(self):
        return json.loads(self.tags)


    class Meta:
        managed = True
        db_table = 'follow_topics'

序列化.py

TopicSeializer 用于 JSON 序列化模型

from rest_framework import serializers 
from .models import Topics
 
 
class TopicSerializer(serializers.ModelSerializer):
    class Meta:
        model = Topics
        fields = ['name_en','name_bn','tags', 'bucket_id']

views.py

get_topic 函数为我提供模型中的主题列表


@api_view(('GET',))
def get_topics(requests):
    topic_id = requests.GET.get('topic_id', None)
    post_data = Topics.objects.filter(bucket_id=topic_id)
    serialize_data = TopicSerializer(post_data, many=True)

    return Response("status": "success", "data": serialize_data)

我得到了可序列化的错误。这个错误看起来让我很沮丧。请帮助我分享一些有用的资源或方法来解决此错误

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/feed/v1/get_topics?topic_id=2

Django Version: 2.1.7
Python Version: 3.6.8
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'debug_toolbar',
 'rest_framework',
 'feedv1']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 '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',
 'corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.BrokenLinkEmailsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware']



Traceback:

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  156.                 response = self.process_exception_by_middleware(e, request)

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  154.                 response = response.render()

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/template/response.py" in render
  106.             self.content = self.rendered_content

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/response.py" in rendered_content
  72.         ret = renderer.render(self.data, accepted_media_type, context)

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in render
  733.         context = self.get_context(data, accepted_media_type, renderer_context)

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in get_context
  688.             'content': self.get_content(renderer, data, accepted_media_type, renderer_context),

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in get_content
  424.         content = renderer.render(data, accepted_media_type, renderer_context)

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in render
  107.             allow_nan=not self.strict, separators=separators

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/utils/json.py" in dumps
  28.     return json.dumps(*args, **kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py" in dumps
  238.         **kw).encode(obj)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in encode
  201.             chunks = list(chunks)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode
  430.             yield from _iterencode_dict(o, _current_indent_level)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode_dict
  404.                 yield from chunks

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode
  437.             o = _default(o)

File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/utils/encoders.py" in default
  68.         return super(JSONEncoder, self).default(obj)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in default
  180.                         o.__class__.__name__)

Exception Type: TypeError at /feed/v1/get_topics
Exception Value: Object of type 'TopicSerializer' is not JSON serializable

【问题讨论】:

【参考方案1】:

您需要访问序列化程序的 .data 属性

return Response("status": "success", "data": <b>serialize_data.data</b>)

【讨论】:

以上是关于TypeError:“TopicSerializer”类型的对象不是 JSON 可序列化的 Django的主要内容,如果未能解决你的问题,请参考以下文章

反应本机获取多标记[未处理的承诺拒绝:TypeError:TypeError:未定义不是对象(评估'this.state.markers.map

Django TypeError - TypeError: issubclass() arg 1 必须是一个类

pyspark:TypeError:'float'对象不可迭代

Python 3.8 TypeError: can't concat str to bytes - TypeError: a bytes-like object is required, not 's

TypeError: key 必须是一个字符串,一个缓冲区或一个对象在 typeError 与 GCP 文件存在

TypeError: jQueryxxxxxx 不是函数